@PropertySource 的详细介绍
功能
该注解可以加载指定的配置文件(*.properties)到 Spring 的 Environment 中。可以配合 @Value 和 @ConfigurationProperties 使用。
- @PropertySource 和 @Value 组合使用,可以将配置文件中的属性值注入到当前类的使用 @Value 注解的成员变量中。
- @PropertySource 和 @ConfigurationProperties 组合使用,可以将配置文件与 Java 类绑定,使用 prefix 指定统一前缀,将配置文件中的属性值与该 Java 类的成员变量一一比较赋值,如果某个变量在配置文件中找不到,会自动赋空(null)。
源码
package org.springframework.context.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.core.io.support.PropertySourceFactory;
@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;
}
使用示例
属性文件:zyc-test.properties
zyc.test.id=1
zyc.test.name=blueribbon
zyc.test.age=23
示例一:@PropertySource + @Value
@Data
@Component
@PropertySource("classpath:zyc-test.properties")
public class ChildWithValue {
@Value("${zyc.test.id}")
private Integer id;
@Value("${zyc.test.name}")
private String name;
@Value("${zyc.test.age}")
private Integer age;
}
示例二:@PropertySource 和 @ConfigurationProperties
@Data
@Component
@PropertySource("classpath:zyc-test.properties")
@ConfigurationProperties(prefix = "zyc.test")
public class ChildWithConfigurationProperties {
private Integer id;
private String name;
private Integer age;
}
示例测试
@Slf4j
@Component
public class CommandRunner implements CommandLineRunner {
@Autowired
ChildWithValue childWithValue;
@Autowired
ChildWithConfigurationProperties childWithConfigurationProperties;
@Override
public void run(String... args) throws Exception {
log.info("使用@PropertySource和@Value给属性赋值:{}", childWithValue.toString());
log.info("使用@PropertySource和@ConfigurationProperties:{}", childWithConfigurationProperties.toString());
}
}
启动项目查看打印结果。