02、@PropertySource指定配置文件的属性映射到JavaBean属性
零、@PropertySource 功能类似于
<context:property-placeholder location="classpath*:/config/load.properties"/>
@Configuration @PropertySources( @PropertySource(value = "classpath:/config/load.properties",ignoreResourceNotFound = true,encoding = "UTF-8") ) public class ServerProperties { @Value("${liubin.test.name}") private String name; public String getName() { return name; } }
一、引入配置文件注解PropertySource源码
package org.springframework.context.annotation;
import ....;
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Repeatable(PropertySources.class)
public @interface PropertySource {
    String name() default "";
    String[] value();//可以是多个
    boolean ignoreResourceNotFound() default false;
    String encoding() default "";
    Class<? extends PropertySourceFactory> factory() default PropertySourceFactory.class;
}
二、PropertySources中包含多个PropertySource
package org.springframework.context.annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface PropertySources { PropertySource[] value(); }
三、引入配置文件后配置项被@Value注解使用
@Component @PropertySource("classpath:teacher.properties") public class Student { @Value("${name}") private String name; @Value("${age}") private int age; @Value("${sex}") private String sex; @Value("${height}") private int height; @Value("${weight}") private int weight; }
四、引入配置文件后配置项被Spring Boot 的@ConfigurationProperties使用,一站式注入到相应的JavaBean的所有属性中
@PropertySource({"classpath:teacher.properties"}) //指定某配置文件,无此参数则在默认全局配置文件中获取
@Component
@ConfigurationProperties(prifix=“teacher”) //配置文件中前缀名为teacher的配置项的所有属性都映射到此JavaBean中
public class Teacher {
    private String name;
    private int age;
    private String sex;
    private int height;
    private int weight;
  get\set方法
}
五、不同的属性配置文件中若有相同的配置项,写在后面配置文件中的属性覆盖前面的
@PropertySources( { @PropertySource("classpath:teacher.properties") } )

 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号