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();
    }
}
原文地址:https://www.cnblogs.com/asksk/p/13596401.html