将配置檔案中的值注入到javaBean實體中
server:
port: 8080
person:
lastName: hello
age: 18
boss: false
birth: 2017/12/12
maps: {k1: v1,k2: 12}
lists:
- lisi
- zhaoliu
dog:
name: 小狗
age: 12
javaBean:
/**
* 将配置檔案中配置的每一個屬性的值,映射到這個元件中
* @ConfigurationProperties:告訴SpringBoot将本類中的所有屬性和配置檔案中相關的配置進行綁定;
* prefix = "person":配置檔案中哪個下面的所有屬性進行一一映射
*
* 隻有這個元件是容器中的元件,才能容器提供的@ConfigurationProperties功能;
*
*/
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
private String lastName;
private Integer age;
private Boolean boss;
private Date birth;
private Map<String,Object> maps;
private List<Object> lists;
private Dog dog;
可以導入配置檔案處理器,以後編寫配置就有提示了
<!--導入配置檔案處理器,配置檔案進行綁定就會有提示-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
properties配置檔案在idea中預設utf-8可能會亂碼
解決方式:

@Value擷取值和@ConfigurationProperties擷取值比較
配置檔案yml還是properties他們都能擷取到值;
如果說,我們隻是在某個業務邏輯中需要擷取一下配置檔案中的某項值,使用@Value;
如果說,我們專門編寫了一個javaBean來和配置檔案進行映射,我們就直接使用@ConfigurationProperties;
配置檔案注入值資料校驗
@Component
@ConfigurationProperties(prefix = "person")
@Validated
public class Person {
/**
* <bean class="Person">
* <property name="lastName" value="字面量/${key}從環境變量、配置檔案中擷取值/#{SpEL}"></property>
* <bean/>
*/
//lastName必須是郵箱格式
@Email
//@Value("${person.last-name}")
private String lastName;
//@Value("#{11*2}")
private Integer age;
//@Value("true")
private Boolean boss;
private Date birth;
private Map<String,Object> maps;
private List<Object> lists;
private Dog dog;
@PropertySource&@ImportResource&@Bean
@PropertySource
:加載指定的配置檔案;
以下表示加載
person.properties
檔案,value的值為數組,表示可以加載多個配置檔案;
@
ImportResource
:導入Spring的配置檔案,讓配置檔案裡面的内容生效
Spring Boot裡面沒有Spring的配置檔案,我們自己編寫的配置檔案,也不能自動識别;
想讓Spring的配置檔案生效,加載進來;@ImportResource标注在一個配置類上
@ImportResource(locations = {"classpath:beans.xml"})
//導入Spring的配置檔案讓其生效
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="helloService" class="com.atguigu.springboot.service.HelloService"></bean>
</beans>
但是springboot不推薦編寫xml配置檔案,推薦使用全注解的方式向容器中添加元件;
通過使用
@Configuration
和
@Bean
給容器中添加元件
/**
* @Configuration:指明目前類是一個配置類;就是來替代之前的Spring配置檔案
*
* 在配置檔案中用<bean><bean/>标簽添加元件
*
*/
@Configuration
public class MyAppConfig {
//将方法的傳回值添加到容器中;容器中這個元件預設的id就是方法名
@Bean
public HelloService helloService02(){
System.out.println("配置類@Bean給容器中添加元件了...");
return new HelloService();
}
}