1. 程式人生 > >【SpringBoot學習之路】06.Springboot配置檔案詳解(二)

【SpringBoot學習之路】06.Springboot配置檔案詳解(二)

轉載宣告:商業轉載請聯絡作者獲得授權,非商業轉載請註明出處.原文來自 © 呆萌鍾 【SpringBoot學習之路】06.Springboot配置檔案詳解(二)

配置檔案值注入

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

image

配置檔案yml還是properties他們都能獲取到值

  • 如果說,我們只是在某個業務邏輯中需要獲取一下配置檔案中的某項值,使用@Value;
  • 如果說,我們專門編寫了一個javaBean來和配置檔案進行對映,我們就直接使用@ConfigurationProperties;

配置檔案注入值資料校驗

@Component
@Validated
@ConfigurationProperties(prefix = "person")
public class Person {

    /**
     * <bean class="Person">
     * <property name="lastName" value="字面量/${key}從環境變數、配置檔案中獲取值/#
     {SpEL}"></property>
     * <bean/>
     */

    //@Value("${person.last-name}")
    @Email
    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:載入指定的配置檔案;

@PropertySource("classpath:person.properties")
@Component
//@Validated
@ConfigurationProperties(prefix = "person")
public class Person {

@ImportResource:匯入Spring的配置檔案,讓配置檔案裡面的內容生效;

Spring Boot裡面沒有Spring的配置檔案,我們自己編寫的配置檔案,也不能自動識別; 想讓Spring的配置檔案生效,載入進來,用@ImportResource標註在一個配置類上

@ImportResource(locations = {"classpath:beans.xml"})
//匯入Spring的配置檔案讓其生效

xml配置檔案

<?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.damienzhong.springboot02config.service.HelloService"></bean>
</beans>

SpringBoot推薦給容器中新增元件的方式;推薦使用全註解的方式

  • 配置類@Configuration------>Spring配置檔案
  • 使用@Bean給容器中新增元件
/**
 * @Configuration:指明當前類是配置類;就是替代之前的Spring配置檔案
 * 在配置檔案中用<bean></bean>標籤要新增
 */
@Configuration
public class MyAppConfig {

    //將方法的返回值新增到容器中;容器中這個元件預設的id就是方法名
    @Bean
    public HelloService helloService(){
        System.out.println("配置類@Bean給容器中新增元件了");
        return  new HelloService();
    }
}

配置檔案佔位符

隨機數

${random.value}、${random.int}、${random.long}
${random.int(10)}、${random.int[1024,65536]}

佔位符獲取之前配置的值,如果沒有可以是用:指定預設值

person.last-name=呆萌鍾${random.uuid}
person.age=${random.int}
person.boss=true
person.birth=2018/10/30
person.maps.k1=v1
person.maps.k2=v2
person.lists=zhangsan,lisi
person.dog.name=${person.hello:哈士奇}_dog
person.dog.age=2