Spring boot = 起步依賴+自動配置
Spring Initializr
- 從本質上來說就是一個Web應用程序,它能為你生成Spring Boot項目結構
Spring Initializr有幾種用法勘纯。
? 通過Web界面使用嫉称。
? 通過Spring Tool Suite使用。
? 通過IntelliJ IDEA使用贪磺。
? 使用Spring Boot CLI使用 - 我使用
- IDEA創(chuàng)建項目->Spring Initializr創(chuàng)建的
- 或命令行:spring init -dweb,data-jpa,mysql,thymeleaf --build maven readinglist拱撵,會自動在當前目錄生成demo.zip辉川,就是完整的基于maven的spring-boot目錄結構
注解
- @SpringBootApplication等效于以下注解組合
- Spring的 @Configuration,基于Java而不是XML的配置
- Spring的 @ComponentScan :啟用組件掃描,自動配置bean
- Spring Boot 的 @EnableAutoConfiguration,開啟了Spring Boot自動配置
外置配置屬性(一)應用程序 Bean
- @ConfigurationProperties 注解可以在控制器中引入乓旗,application.yml自定義的配置屬性變量,前提是必須導入依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
-
HelloWorld控制器
@RestController //使用application.yml中的lxf-customer前綴的自定義屬性 @ConfigurationProperties(prefix = "lxf-customer") public class HelloWorld { private final Logger logger = LoggerFactory.getLogger(HelloWorld.class); //定義username屬性屿愚,可以通過@ConfigurationProperties注解接收application.yml配置的自定義屬性,必須配置setUserename方法 private String username; public void setUsername(String username) { this.username = username; } @GetMapping(value = "/hello") public String testHello() { return "hello world!" + username ; } }
以上例子我們也可以把,username自定義屬性相關的信息放在一個單獨的Bean中务荆,比如:
CustomerProperties
package com.example.readinglist.others;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* 自定義屬性
*/
@Component
//帶有l(wèi)xf-customer前綴的屬性妆距,在application.yml中定義
@ConfigurationProperties("lxf-customer")
public class CustomerProperties {
private String username;
public void setUsername(String username) {
this.username = username;
}
public String getUsername() {
return username;
}
}
此時在HelloWorld
中使用application.yml在自定義的username屬性:
@RestController
//使用application.yml中的lxf-customer前綴的自定義屬性
@ConfigurationProperties(prefix = "lxf-customer")
public class HelloWorld {
@Autowired
//自定義屬性文件,該文件通過@ConfigurationProperties("lxf-customer")
//獲取application.yml中的lxf-customer.username屬性
private CustomerProperties customerProperties;
@GetMapping(value = "/hello")
public String testHello()
{
return "hello world!" + customerProperties.getUsername() ;
}
}
外置配置屬性(二)Profile條件化配置
- 針對不同環(huán)境的不同配置:http://m.blog.csdn.net/lazycheerup/article/details/51915185
-
使用@Profile注解
profiles.jpg