一、Spring Boot基本配置
1、入口類和@SpringBootApplication
Spring Boot通常有一個名為*Application的入口類,入口類中有一個main方法,這個main方法其實就是一個標準的Java應用程序的入口方法。在main方法中使用SpringApplication.run(Chapter01Application.class, args),啟動Spring Boot應用項目。
2、關閉特定的自動配置
通過@SpringBootApplication源碼可以看出,關閉特定的自動配置應該使用@SpringBootApplication注解的exclude參數(shù),例如:
@SpringBootApplication(exclude={DataSourceAutoConfiguration.class})
3、定制Banner
在Spring Boot啟動的時候會有一個默認啟動圖案,這個圖案是可以自定義的。
1)我們在src/main/resources下新建一個banner.txt
2)通過http://patorjk.com/software/taag網(wǎng)站生成字符,將生成的字符復制到banner.txt文件中
3)自動程序,這時控制臺圖案將變成剛才生成的圖案
4、關閉banner
在main方法中修改為(Spring Boot:1.4.0):
SpringApplication application = new SpringApplication(Chapter1Application.class);
application.setBannerMode(Mode.OFF);
application.run(args);
或者
new SpringApplicationBuilder(Chapter1Application.class) //
.bannerMode(Mode.OFF) //
.run(args);
5、Spring Boot配置文件
Spring Boot使用一個全局的配置文件application.properties或application.yml,放置在src/main/resources目錄或者類路徑的/config下。<p>
Spring Boot不僅支持常規(guī)的properties配置文件,還支持yaml語言的配置文件。yaml是以數(shù)據(jù)為中心的語言,在配置數(shù)據(jù)的時候具有面向對象的特征。<p>
Spring Boot的全局配置文件的作用是對一些默認配置值進行修改。
例如:
修改tomcat端口為8080->8888,默認的訪問路徑為"/"->”/helloboot”??梢栽?br>
application.properties中添加:
server.port=9090
server.context-path=/helloBoot
6、官方starter pom
<div style="color:gray">
spring-boot-starter ?????Spring Boot核心starter,包含自動配置、日志、yaml配置文件的支持
spring-boot-starter-actuator ????? 準生產(chǎn)特性,用來監(jiān)控和管理應用
spring-boot-starter-remote-shell ????? 提供基于ssh協(xié)議的監(jiān)控和管理
spring-boot-starter-amqp ????? 使用spring-rabbit來支持AMQP
spring-boot-starter-aop ????? 使用spring-aop和AspectJ支持面向切面變成
spring-boot-starter-batch ????? 對Spring Batch的支持
spring-boot-starter-cache ????? 對Spring Cache抽象的支持
spring-boot-starter-cloud-connectors ????? 對云平臺(Cloud Foundry,Heroku)提供的服務提供簡化的連接方法
spring-boot-starter-data-elasticsearch ????? 通過spring-data-elasticsearch對Elasticsearch的支持
spring-boot-starter-data-gemfire ????? 通過spring-data-gemfire對分布式存儲GenFile的支持
spring-boot-starter-data-jpa ????? 對JPA的支持,包含spring-data-jpa,spring-orm和Hibernate
spring-boot-starter-data-mongodb ????? 通過spring-data-mongodb,對MongoDB進行支持
spring-boot-starter-data-rest ????? 通過spring-data-rest-webmvc將Spring Data Repository暴露REST形式的服務
spring-boot-starter-data-solr ????? 通過spring-data-solr對Apache Solr數(shù)據(jù)檢索平臺的支持
spring-boot-starter-freemarker ????? 對FreeMarker模板引擎的支持
spring-boot-starter-groovy-templates ????? 對Groovy模板引擎的支持
spring-boot-starter-hateoas ????? 通過spring-hateoas 通過spring-hateoas對基于HATEOAS的REST形式的網(wǎng)絡服務的支持
spring-boot-starter-hornetq ????? 通過HornetQ對JMS的支持
spring-boot-starter-integration ????? 對系統(tǒng)集成框架spring-integration的支持
spring-boot-starter-jdbc ????? 對JDBC數(shù)據(jù)庫的支持
spring-boot-starter-jersey ????? 對Jersery REST形式的網(wǎng)絡服務的支持
spring-boot-starter-jta-atomikos ????? 通過Atomikos對分布式事務的支持
spring-boot-starter-jta-bitronix ????? 通過Bitronix對分布式事務的支持
spring-boot-starter-mail ????? 對javax.mail的支持
spring-boot-starter-mobile ????? 對spring-mobile的支持
spring-boot-starter-mustache ????? 對Mustache模板引擎的支持
spring-boot-starter-redis ????? 對鍵值對內存數(shù)據(jù)庫Redis的支持,包含spring-reids
spring-boot-starter-security ????? 對spring-security的支持
spring-boot-starter-social-faceboot ????? 通過spring-social-faceboot對Facebook的支持
spring-boot-starter-social-twitter ????? 通過spring-social-twitter對Twitter的支持
spring-boot-starter-test ????? 對常用的測試框架Junit,Hamcrest和Mockito的支持,包含spring-test模板
spring-boot-starter-thymeleaf ????? 對Thymeleaf模板引擎的支持,包含于Spring整合的配置
spring-boot-starter-velocity ????? 對Velocity模板引擎的支持
spring-boot-starter-web ????? 對Web項目開發(fā)的支持,包含Tomcat和spring-webmvc
spring-boot-starter-Tomcat ????? Spring Boot默認的Servlet容器Tomcat
spring-boot-starter-Jetty ????? 使用Jetty作為Servlet容器替換Tomcat
spring-boot-starter-undertow ????? 使用Undertow作為Servlet容器替換Tomcat
spring-boot-starter-logging ????? Spring Boot默認的日志框架Logback
spring-boot-starter-log4j ????? 支持使用Log4j日志框架
spring-boot-starter-websocket ????? 對WebSocket開發(fā)的支持
spring-boot-starter-ws ?????對Spring Web Services的支持
</div>
<p>
還有第三方為Spring Boot所寫的starter pom,這里不做介紹
7、使用xml配置
Spring Boot提倡零配置,即無xml配置,但是在實際項目中,可能有些特殊要求,使得開發(fā)者必須使用xml配置,這時我們可以通過Spring提供的@ImportResource來加載xml配置,例如:
@ImportResource({"classpath:context.xml”})
8、命令行參數(shù)配置
Spring Boot可以是基于jar包運行的,打成jar包的程序可以直接通過java -jar xx.jar來運行
可以通過java -jar xx.jar —server.port=8888來修改Tomcat端口號
9、常規(guī)屬性配置
在常規(guī)Spring環(huán)境下,注入properties文件里的值得方式,通過@PropertySource指明properties文件的位置,然后通過@Value注入值。在Spring Boot里,只需要在application.properties定義屬性,直接使用@Value注入即可。
例如:
在application.properties文件中添加屬性:
book.author=cm
book.name=spring boot
在com.gnd.springboot.config.init路徑下新建PropertiesTests屬性配置類,使用@Value注入book屬性
@Component
public class PropertiesTests {
@Value("book.author")
private String author;
@Value("book.name")
private String name;
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
10、類型安全的配置(基于properties)
Spring Boot提供了基于類型安全的配置方式,通過@ConfigurationProperties將properties屬性和一個Bean及其屬性關聯(lián),從而實現(xiàn)類型安全的配置。所以,常規(guī)屬性配置可以修改為:
@Component
@ConfigurationProperties(prefix = "book")
public class PropertiesTests {
private String author;
private String name;
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
11、日志配置
Spring Boot支持Java Util Logging、Log4J、Log4J2和Logback作為日志框架,無論使用哪種日志框架,Spring Boot已為當前使用日志框架的控制臺輸出及文件輸出做好了配置。<p>
默認情況下,Spring Boot使用Logback作為日志框架。日志級別:****logging.file=/home/cm/mylog.log****
配置日志文件,格式為logging.level.包名=級別:****logging.level.org.springframework.web=DEBUG****
12、Profile配置
Profile是Spring用來針對不同的環(huán)境對不同的配置提供支持的,全局Profile配置使用application-{profile}.properties(如application-prod.properties),
通過在application.properties中設置****spring.profiles.active=prod****來指定活動的Profile
例如:
我們分為生產(chǎn)(prod)和開發(fā)(dev)環(huán)境,在生產(chǎn)環(huán)境下端口號為80,開發(fā)環(huán)境為8888。
兩種配置文件分別為:
application-prod.properties: server.port=80
application-dev.properties: server.port=8888
然后在application.properties增加:
spring.profiles.active=dev(prod)
通過Profile可以靈活切換Spring Boot項目的配置了。
二、Spring Boot運行原理
Spring Boot關于自動配置的源碼在spring-boot-autoconfigure-1.4.0.RELEASE.jar內,主要包含了以下配置:<p>
<a title="點擊顯示原始圖片"><img src="http://i1.piimg.com/4851/bb6e18a430a22a09t.jpg"></a>
<a title="點擊顯示原始圖片"><img src="http://i1.piimg.com/4851/73ed190dbda257cbt.jpg"></a><p>
若想知道Spring Boot為我們做了哪些自動配置,可以通過通過三種方式查看以啟用和未啟用的自動配置的報告:<p>
1)運行jar時增加—debug參數(shù):java -jar xx.jar —debug<p>
2)在application.properties中設置屬性:debug=true(這個方便點)<p>
3)在開發(fā)工具啟動參數(shù)中配置<p>
<a title="點擊顯示原始圖片"><img src="http://i1.piimg.com/4851/db0610f744b512ect.jpg"></a><p>
1、Spring Boot運行原理解析:
對@SpringBootApplication注解說明:
@SpringBootApplication是一個組合注解,它的核心功能是由@EnableAutoConfiguration注解提供的。
查看@EnableAutoConfiguration源碼<p>
<a title="點擊顯示原始圖片"><img src="http://i1.piimg.com/4851/df2b568388d67082t.jpg"></a><p>
這里@Import注解導入配置功能,EnableAutoConfigurationImportSelector使用SpringFactoriesLoader.loadFactoryNames方法來掃描具有META-INF/spring.factories文件的jar包,而spring-boot-autoconfigure-1.4.0.RELEASE.jar里就有一個spring.factories文件,次問價中聲明了有哪些自動配置。
<a title="點擊顯示原始圖片"><img src="http://i1.piimg.com/4851/8290194ff6bbbda5t.jpg"></a>
<a title="點擊顯示原始圖片"><img src="http://i1.piimg.com/4851/dba6c685c8097175t.jpg"></a><p>
? 任意打開一個AutoConfiguration文件,一般都有以下條件注解,在spring-boot-autoconfigure-1.4.0.RELEASE.jar的org.springframework.boot.autoconfigure.condition包下,條件注解如下:<p>
<div style="color:gray">
@ConditionalOnBean: ????? 當容器里有指定的Bean的條件下
@ConditionalOnClass: ????? 當類路徑下有指定的類的條件下
@ConditionalOnExpression: ????? 基于SpEL表達式作為判斷條件
@ConditionalOnJava: ????? 基于JVM版本作為判斷條件
@ConditionalOnJndi: ????? 在JNDI存在的條件下查找指定的位置
@ConditionalOnMissingBean: ????? 當容器里沒有指定Bean的情況下
@ConditionalOnMissingClass: ????? 當類路徑下沒有指定的類的條件下
@ConditionalOnNotWebApplication: ????? 當前項目不是Web項目的條件下
@ConditionalOnProperty: ????? 指定的屬性是否有指定的值
@ConditionalOnResource: ????? 類路徑是否有指定的值
@ConditionalOnSingleCandidate: ????? 當指定Bean在容器中只有一個,或者雖然有多個但是指定首選的Bean
@ConditionalOnWebApplication: ????? 當前項目是Web項目的條件下
</div><p>
這些注解都是使用了@Conditional元注解,不過是使用了不同的條件而已。
2、分析http的編碼配置
配置參數(shù)
HttpEncodingProperties的源碼如下:<p>
<a title="點擊顯示原始圖片"><img src="http://i1.piimg.com/4851/01b5f66dfd191b68t.jpg"></a><p>
這里的配置類可以直接在application.properties中以spring.http.encoding 為前綴配置,比如:如果需要修改默認編碼方式,可通過spring.http.encoding.charset=gbk 配置。
根據(jù)條件配置CharacterEncodingFilter的Bean,源碼如下:
<a title="點擊顯示原始圖片"><img src="http://i1.piimg.com/4851/6307e6e411a78c22t.jpg"></a>
3、自定義自動配置(包裝成starter pom)
1)新建maven工程spring-boot-starter-hello,在pom.xml中添加如下配置:
<properties>
<spring-framework.version>1.4.0.RELEASE</spring-framework.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
<version>${spring-framework.version}</version>
</dependency>
</dependencies>
- 新建屬性配置類HellpServiceProperties
@ConfigurationProperties(prefix = "hello")
public class HelloServiceProperties {
private static final String MSG = "world";
private String msg = MSG;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
此種配置方式為類型安全的屬性獲取。在application.properties中通過hello.msg= 來設置,若不設置,默認為hello.msg=world<p>
3)新建依據(jù)類HelloService(此類可以是第三方類庫的類)
public class HelloService {
private String msg;
public String sayHello() {
return "Hello " + msg;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
4)新建自動配置類
@Configuration
@EnableConfigurationProperties(HelloServiceProperties.class)
@ConditionalOnClass(HelloService.class)
@ConditionalOnProperty(prefix = "hello", value = "enabled", matchIfMissing = true)
public class HelloServiceAutoConfiguration {
@Autowired
private HelloServiceProperties helloServiceProperties;
@Bean
@ConditionalOnMissingBean(HelloService.class)
public HelloService helloService() {
HelloService helloService = new HelloService();
helloService.setMsg(helloServiceProperties.getMsg());
return helloService;
}
}
根據(jù)HelloServiceProperties提供的參數(shù),并通過@ConditionalOnClass來判斷HelloService這個類在類路徑中是否存在,且當這個容器中沒有這個Bean的情況下自動配置這個Bean。<p>
5)注冊自動配置<p>
在src/main/resources中新建META-INF/spring.factories文件,內容為
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ com.gnd.springboot.config.HelloServiceAutoConfiguration<br>
其中“\”是為了在換行之后仍能讀到屬性,若有多個自動配置,以“,”分隔<p>
6)測試自定義自動配置<p>
新建一個maven web工程,添加如下依賴:
<properties>
<spring-framework.version>1.4.0.RELEASE</spring-framework.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>spring-boot-starter-hello</groupId>
<artifactId>com.gnd.springboot</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
spring-boot-starter-hello為之前新建的自定義自動配置starter pom<p>
新建測試啟動類
?
@RestController
@SpringBootApplication
public class Chapter11Application {
@Autowired
private HelloService helloService;
@RequestMapping("/test")
public String index() {
return helloService.sayHello();
}
public static void main(String[] args){
SpringApplication.run(Chapter11Application.class, args);
}
}
運行測試工程之后,瀏覽器輸入"http://localhost:8080/test"測試,測試結果如下:
<a title="點擊顯示原始圖片"><img src="http://p1.bpimg.com/4851/6ff00c546916cb99t.jpg"></a><p>
新建application.properties配置文件,內容為
hello.msg=haha
重啟工程,瀏覽器輸入"http://localhost:8080/test"測試
關注我的微信公眾號:FramePower
我會不定期發(fā)布相關技術積累,歡迎對技術有追求、志同道合的朋友加入,一起學習成長!
