【Spring Boot】 從入門到熟練,從簡介到集成

一、     簡介

         Spring BootSpring社區較新的一個項目。該項目的目的是幫助開發者更容易的創建基於Spring的應用程序和服務,讓更多人的人更快的對Spring進行入門體驗,讓Java開發也能夠實現Ruby on Rails那樣的生產效率。爲Spring生態系統提供了一種固定的、約定優於配置風格的框架。

 

         Spring Boot具有如下特性:

·        爲基於Spring的開發提供更快的入門體驗

·        開箱即用,沒有代碼生成,也無需XML配置。同時也可以修改默認值來滿足特定的需求。

·        提供了一些大型項目中常見的非功能性特性,如嵌入式服務器、安全、指標,健康檢測、外部配置等。

·        Spring Boot並不是不對Spring功能上的增強,而是提供了一種快速使用Spring的方式。

 

二、     基礎配置

         SpringBoot 使用Maven進行配置,首先新建一個maven項目,在pom.xml裏添加如下:

 

    <parent>

        <groupId>org.springframework.boot</groupId>

        <artifactId>spring-boot-starter-parent</artifactId>

        <version>1.3.0.RELEASE</version>

    </parent>

         增加父pom比較簡單,而且spring-boot-starter-parent包含了大量配置好的依賴管理,在自己項目添加這些依賴的時候不需要寫<version>版本號。

         使用父pom雖然簡單,但是有些情況我們已經有父pom,不能直接增加<parent>時,可以通過如下方式:

<dependencyManagement>

     <dependencies>

        <dependency>

            <!-- Importdependency management from Spring Boot -->

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-dependencies</artifactId>

            <version>1.2.3.RELEASE</version>

            <type>pom</type>

            <scope>import</scope>

        </dependency>

    </dependencies>

</dependencyManagement>

 

         Spring通過添加spring-boot-starter-* 這樣的依賴就能支持具體的某個功能。我們最終是要實現web功能,所以添加的是這個依賴。

 

    <dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-starter-web</artifactId>

     </dependency>

 

         可以使用java.version 直接配置使用的java版本:

 

    <properties>

         <java.version>1.8</java.version>

    </properties>

 

 

三、     一個簡單的運行

 

         創建一個簡單的類:

 

         @RestController

    @SpringBootApplication

    publicclassApplication {

 

        @RequestMapping("/")

       String home() {

           return"HelloWorld!";

        }

 

        @RequestMapping("/now")

       String hehe() {

            return"現在時間:" + (new Date()).toLocaleString();

        }

 

        publicstaticvoidmain(String[] args) {

            SpringApplication.run(Example.class, args);

        }

 

    }

 

Spring Boot建議將我們main方法所在的這個主要的配置類配置在根包名下。

類似如下結構:

com

 +- example

    +- myproject

        +- Application.java

        |

        +- domain

        |   +- Customer.java

        |   +- CustomerRepository.java

        |

        +- service

        |   +- CustomerService.java

        |

        +- web

             +- CustomerController.java

 

 

@RestController

因爲我們例子是寫一個web應用,因此寫的這個註解,這個註解相當於同時添加@Controller@ResponseBody註解。

 

@SpringBootApplication

包含了@Configuration,@EnableAutoConfiguration,@ComponentScan三個註解。Spring Boot建議只有一個帶有該註解的類。該註解告訴了Spring Boot程序的入口。

 

啓動Spring Boot項目

啓動Spring Boot項目最簡單的方法就是執行下面的方法:

SpringApplication.run(Application.class, args);

·        1

該方法返回一個ApplicationContext對象,使用註解的時候返回的具體類型是AnnotationConfigApplicationContextAnnotationConfigEmbeddedWebApplicationContext,當支持web的時候是第二個。

除了上面這種方法外,還可以用下面的方法:

SpringApplication application = newSpringApplication(Application.class);

application.run(args);

 

SpringApplication包含了一些其他可以配置的方法,如果你想做一些配置,可以用這種方式。

IDE中直接直接執行main方法,然後訪問http://localhost:8080就可以訪問到這個項目了。

 

四、     Spring Boot的屬性配置

         Spring Boot 允許通過外部配置讓你在不同的環境使用同一應用程序的代碼,簡單說就是可以通過配置文件來注入屬性或者修改默認的配置。

 

         這些方式優先級如下:

1.       命令行參數

2.       來自java:comp/envJNDI屬性

3.       Java系統屬性(System.getProperties()

4.       操作系統環境變量

5.       RandomValuePropertySource配置的random.*屬性值

6.       jar包外部的application-{profile}.propertiesapplication.yml(spring.profile)配置文件

7.       jar包內部的application-{profile}.propertiesapplication.yml(spring.profile)配置文件

8.       jar包外部的application.propertiesapplication.yml(不帶spring.profile)配置文件

9.       jar包內部的application.propertiesapplication.yml(不帶spring.profile)配置文件

10.    @Configuration註解類上的@PropertySource

11.    通過SpringApplication.setDefaultProperties指定的默認屬性

 

 

命令行參數:

通過java -jarapp.jar --name="Spring" --server.port=9090方式來傳遞參數。

參數用--xxx=xxx的形式傳遞。

可以使用的參數可以是我們自己定義的,也可以是SpringBoot中默認的參數。

 

配置文件:

配置文件名爲application.propertiesapplication.ymlspring boot會從classpath下的/config目錄或者classpath的根目錄查找application.propertiesapplication.yml

 

.properties配置文件如:

name=Isea533
server.port=8080

.yml格式的配置文件如:

name: Isea533
server:
    port: 8080
 

常用配置:

         server.port                         web服務器訪問端口

    server.context-path                 web服務訪問名

    spring.datasource.url                   數據庫連接URL
    spring.datasource.username             
數據庫連接用戶名
    spring.datasource.password             
數據庫連接密碼

    spring.datasource.driver-class-name 數據庫連接驅動

具體其他配置可以點擊這裏查看

 

五、     Spring Boot 與持久層

SpringBoot 與Mybatis

         首先需要配置好數據源:

                   spring:

             datasource:

                  name:test

                  url:jdbc:mysql://192.168.16.137:3306/test

                username: root

                password:

                # 使用druid數據源

                type: com.alibaba.druid.pool.DruidDataSource

                driver-class-name: com.mysql.jdbc.Driver

                filters: stat

                maxActive: 20

                initialSize: 1

                maxWait: 60000

                minIdle: 1

                timeBetweenEvictionRunsMillis: 60000

                minEvictableIdleTimeMillis: 300000

                validationQuery: select 'x'

                testWhileIdle: true

                testOnBorrow: false

                testOnReturn: false

                poolPreparedStatements: true

                 maxOpenPreparedStatements: 20

 

         然後在pom.xml配置Mybatis依賴:mybatis-spring-boot-starter

        <dependency>

             <groupId>org.mybatis.spring.boot</groupId>

             <artifactId>mybatis-spring-boot-starter</artifactId>

             <version>1.0.0</version>

        </dependency>

 

         application.yml中增加配置:

                   mybatis:

                          mapperLocations:classpath:mapper/*.xml

                          typeAliasesPackage:tk.mapper.model

除了上面常見的兩項配置,還有:

·        mybatis.configmybatis-config.xml配置文件的路徑

·        mybatis.typeHandlersPackage:掃描typeHandlers的包

·        mybatis.checkConfigLocation:檢查配置文件是否存在

·        mybatis.executorType:設置執行模式(SIMPLE, REUSE,BATCH),默認爲SIMPLE

 

配置完這些就可以正常使用Mybatis了。

SpringBoot 與Redis

引入 spring-boot-starter-redis

<dependency>

         <groupId>org.springframework.boot</groupId>

         <artifactId>spring-boot-starter-redis</artifactId>

 </dependency>

添加配置文件

# REDIS (RedisProperties)

# Redis數據庫索引(默認爲0

spring.redis.database=0

# Redis服務器地址

spring.redis.host=192.168.0.58

# Redis服務器連接端口

spring.redis.port=6379

# Redis服務器連接密碼(默認爲空)

spring.redis.password=

# 連接池最大連接數(使用負值表示沒有限制)

spring.redis.pool.max-active=8

# 連接池最大阻塞等待時間(使用負值表示沒有限制)

spring.redis.pool.max-wait=-1

# 連接池中的最大空閒連接

spring.redis.pool.max-idle=8

# 連接池中的最小空閒連接

spring.redis.pool.min-idle=0

# 連接超時時間(毫秒)

spring.redis.timeout=0

 

配置完這些,就可以用基本的redis操作了

@Autowired

private StringRedisTemplatestringRedisTemplate;

@Autowired

private RedisTemplate redisTemplate;

@Test

public void test() throws Exception {

    stringRedisTemplate.opsForValue().set("aaa","111");

    Assert.assertEquals("111",stringRedisTemplate.opsForValue().get("aaa"));

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章