Spring boot Value注入 未整理 待完善


 

Springboot 熱部署
Springboot為開發者提供了一個名叫 spring-boot-devtools來使Springboot應用支持熱部署,提供開發者的開發效率,無需手動重啟Spring Boot應用

<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-devtools -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<version>2.1.3.RELEASE</version>
</dependency>

  


導入配置文件處理器,以后會出現提示

<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-configuration-processor -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<version>2.1.3.RELEASE</version>
</dependency>

  


注意: Properties配置文件在idea中默認utf-8可能會亂碼


配置文件中,我們可以自己制定配置數據源
通過type來選擇使用哪種數據庫


Springboot自動配置原理
1. Springboot啟動的時候加載主配置類,開啟了自動配置功能@EnableAutoConfiguration
2. @EnableAutoConfiguration的作用
3.

 

@Value獲取值和@ConfigurationProperties獲值比較

 


配置文件是yml還是properties 他們都能夠獲取到值
如果說,我們只是在某個業務邏輯領域,需要獲取一下配置文件中的某項值,使用@Value
如果說,我們專門編寫了一個javaBean來和配置文件進行映射,我們就直接使用@ConfigurationProperties

@ConfigurationProperties
該注解可以將配置文件中配置的每一個屬性的值,通過set方法映射到被注釋的組件中(因此不可以缺少setter方法)

/**
* 批量注入、松散綁定、數據校驗、復雜類型封裝
*/
@Component
@ConfigurationProperties(prefix = "person1") //批量注入
@Validated //數據校驗
public class Person {
@Email
private String lastName;
private Integer age;
private Boolean boss;
private Date birth;
private Map<String,Object> maps;
private List<Object> lists;
private Dog dog;//復雜類型封裝

public void setLastName(String lastName) {
this.lastName = lastName;
}
......
}
public class Dog {
private String name;
private Integer age;
public void setName(String name) {
this.name = name;
}
public void setAge(Integer age) {
this.age = age;
}
}

applicaton.yml

person1:
lastName: 888888@qq.com
#以下二種寫法與上述等同(松散綁定):
#last-name: 88888@qq.com
#last_name: 88888@qq.com
age: 18
boss: false
birth: 2018/04/04
maps: {k1: v1,k2: v2}
lists:
- lisi
- zhaoliu
dog:
name: 小狗
age: 12


@Value
@Component
@Validated
public class Person {
@Email//數據校驗無效
@Value("${person1.lastName}")//從環境變量、配置文件中獲取值
private String lastName;
@Value("#{11*2}")//使用SpEL表達式
private Integer age;
@Value("true")//直接賦值
private Boolean boss;
private Date birth;
@Value("${person1.maps}")//不支持復雜類型,報錯
private Map<String,Object> maps;
private List<Object> lists;
private Dog dog;
......
}


@PropertySource、@ImportResource、@Bean
//指明當前類為配置類,替代之前的Spring配置文件
@Configuration
//加載指定的配置文件
@PropertySource(value = {"classpath:person.properties"})
//SpringBoot項目沒有Spring的配置文件,若要想自己編寫Spring配置文件加載並生效,需要使用@ImportResoure注解標注在一個配置類上
@ImportResource(locations = {"classpath:application.xml"})
public class MyAppConfig {

@Bean //注冊bean,默認是方法名作為id
public Person person() {
return new Person();
}
}


SpringBoot給容器中添加組件的方式(推薦使用全注解的方式):

配置類@Configuration標注@ImportResoure加載Spring配置文件
使用@Bean給容器中添加組件
3.3 配置文件屬性
3.3.1 隨機數
RandomValuePropertySource:配置文件中可以使用隨機數

${random.value}:隨機數字與字母組合的字符串
${random.uuid}:隨機uuid
${random.long}:隨機long值
${random.int}:隨機int值
${random.int(value)}:0~value之間的隨機數
${random.int(value,max)}:value~max之間的隨機數
這些隨機數可以使用在配置文件或@Value注解中

person1:
lastName: ${random.value}
age: ${random.int(0,100)}
#如果birthday不存在使用默認值2014/1/1
birth: ${birthday:2014/1/1}


3.3.2 profile
Profile是Spring對不同環境提供不同配置功能的支持,可以通過激活、指定參數等方式快速切換環境,多環境有以下二種方式:

多個profile文件:格式是application-{profile}.properties/yml,例如application-dev.properties,SpringBoot默認加載application.propeties/yml配置文件,可以在該文件中激活不同的profile:spring.profiles.active=dev
多個profile文檔塊模式application.yml:


#激活指定環境

spring:
profiles:
active: dev

---

#開發環境

spring:
profiles: dev
server:
port: 8090

---

#生產環境

spring:
profiles: product
server:
port: 9090

---

#默認環境

spring:
profiles: default
server:
port: 8080

配置環境也可以在外部文件、命令行或jvm參數中指定,如使用命令行(- -spring.profiles.active=dev)或jvm參數(-Dspring.profiles.active=dev)來激活指定的profile。

3.3.3 配置文件加載順序
springboot 啟動會掃描以下位置的application.properties或者application.yml文件作為Spring boot的默認配置文件

file:./config/
file:./
classpath:/config/
classpath:/
上述優先級由高到低,高優先級的配置會覆蓋低優先級的配置,同時配置互補。項目打包好以后,我們可以使用命令行參數的形式,啟動項目的時候來可以使用spring.config.location指定外部的配置文件位置:

java -jar spring-boot-0.0.1-SNAPSHOT.jar --spring.config.location=D:/application.properties
1
springboot的所有配置都可以在命令行上指定,多個配置使用空格分開,spring配置的優先級由高到低:

命令行參數
來自java:comp/env的JNDI屬性
Java系統屬性(System.getProperties())
操作系統環境變量
RandomValuePropertySource配置的random.*屬性值
jar包外部的application-{profile}.properties或application.yml(帶spring.profile)配置文件
jar包內部的application-{profile}.properties或application.yml(帶spring.profile)配置文件
jar包外部的application.properties或application.yml(不帶spring.profile)配置文件
jar包內部的application.properties或application.yml(不帶spring.profile)配置文件
@Configuration注解類上的@PropertySource
通過SpringApplication.setDefaultProperties指定的默認屬性
4. 自動配置原理
SpringBoot啟動的時候加載主配置類(@SpringBootApplication),開啟了自動配置功能@EnableAutoConfiguration
@EnableAutoConfiguration的組合注解@AutoConfigurationPackage將該配置類包及子包路徑下的所有組件掃描進Spring容器中
@EnableAutoConfiguration的組合注解 @Import(AutoConfigurationImportSelector.class)注解導入AutoConfigurationImportSelector類,AutoConfigurationImportSelector類實現了DeferredImportSelector接口重寫了selectImports方法,SpringFactoriesLoader.loadFactoryNames()掃描所有jar包類路徑下 META-INF/spring.factories把掃描到的這些文件的內容包裝成List對象,selectImports將這些自動配置類注冊到容器中
4.1 自動配置類案例分析
以HttpEncodingAutoConfiguration 這個自動配置類為例:

@Configuration //標注該類為配置類
@EnableConfigurationProperties(HttpEncodingProperties.class) //啟動指定類的ConfigurationProperties功能,將配置文件中對應的值和HttpEncodingProperties綁定起來,並把HttpEncodingProperties加入到ioc容器中
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET) //只有基於Servlet的web環境配置類才會生效
@ConditionalOnClass(CharacterEncodingFilter.class) //判斷當前項目有沒有CharacterEncodingFilter這個類,CharacterEncodingFilter是SpringMVC中進行亂碼解決的過濾器
@ConditionalOnProperty(prefix = "spring.http.encoding", value = "enabled", matchIfMissing = true)//判斷配置文件中是否存在spring.http.encoding.enabled這個配置,如果缺失則默認為true
public class HttpEncodingAutoConfiguration {

private final HttpEncodingProperties properties;
//將與SpringBoot配置文件映射過的HttpEncodingProperties注入
public HttpEncodingAutoConfiguration(HttpEncodingProperties properties) {
this.properties = properties;
}
//若容器中沒有CharacterEncodingFilter這個組件就注入該bean
@Bean
@ConditionalOnMissingBean(CharacterEncodingFilter.class)
public CharacterEncodingFilter characterEncodingFilter() {
CharacterEncodingFilter filter = new OrderedCharacterEncodingFilter();
filter.setEncoding(this.properties.getCharset().name());
filter.setForceRequestEncoding(this.properties.shouldForce(HttpEncodingProperties.Type.REQUEST));
filter.setForceResponseEncoding(this.properties.shouldForce(HttpEncodingProperties.Type.RESPONSE));
return filter;
}

@Bean
public LocaleCharsetMappingsCustomizer localeCharsetMappingsCustomizer() {
return new LocaleCharsetMappingsCustomizer(this.properties);
}

private static class LocaleCharsetMappingsCustomizer implements
WebServerFactoryCustomizer<ConfigurableServletWebServerFactory>, Ordered {

private final HttpEncodingProperties properties;

LocaleCharsetMappingsCustomizer(HttpEncodingProperties properties) {
this.properties = properties;
}

@Override
public void customize(ConfigurableServletWebServerFactory factory) {
if (this.properties.getMapping() != null) {
factory.setLocaleCharsetMappings(this.properties.getMapping());
}
}

@Override
public int getOrder() {
return 0;
}
}
}

HttpEncodingProperties類映射配置文件中以spring.http.encoding為前綴的配置

@ConfigurationProperties(
prefix = "spring.http.encoding"
)
public class HttpEncodingProperties {
public static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;

/**
* Charset of HTTP requests and responses. Added to the "Content-Type" header if not
* set explicitly.
*/
private Charset charset = DEFAULT_CHARSET;

/**
* Whether to force the encoding to the configured charset on HTTP requests and
* responses.
*/
private Boolean force;

/**
* Whether to force the encoding to the configured charset on HTTP requests. Defaults
* to true when "force" has not been specified.
*/
private Boolean forceRequest;

/**
* Whether to force the encoding to the configured charset on HTTP responses.
*/
private Boolean forceResponse;

/**
* Locale in which to encode mapping.
*/
private Map<Locale, Charset> mapping;
.......
}

application.yml

#yml中可配置的屬性也都是根據這些類中的屬性來指定
spring:
http:
encoding:
enabled: true
charset: utf-8
force: true
force-request: true
force-response: true
mapping: UTF-8

 

 

 

 

Springboot常用的模板引擎
JSP、Velecity、Freemaker、Thymeleaf

 

 

 


jdbcTemplate

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM