SpringBoot引用配置文件


1.@ConfigurationProperties(prefix = "person")

引用application.properties全局文件中的person開頭的屬性,只有這個組件是容器中的組件,才能容器提供的@ConfigurationProperties功能(一般與@Component同時使用);

支持@Validated校驗

2.@Value("${person.last-name}")

引用單獨的屬性,不支持@Validated校驗

@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;

3.@PropertySource:加載指定的配置文件;

@PropertySource(value = {"classpath:person.properties"})

與@ConfigurationProperties區別在於,@PropertySource可以引用指定的配置文件而非默認的application.properties文件

4.@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>

5.@Configuration

@Configuration:指明當前類是一個配置類;就是來替代之前的Spring配置文件

使用@Bean給容器中添加組件

@Configuration
public class MyAppConfig {

    //將方法的返回值添加到容器中;容器中這個組件默認的id就是方法名
    @Bean
    public HelloService helloService02(){
        System.out.println("配置類@Bean給容器中添加組件了...");
        return new HelloService();
    }
}

 


免責聲明!

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



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