问题
@PropertySource与@ImportResource长得很像,作用也有一定类似,现在就来好好区分一下吧!
@PropertySource
加载自定义配置文件(*.properties或 *.yml),通常需要结合@Configuration注解共同使用。
test.properties配置文件
test.id=110
test.name=test
注入配置的类示例
//表示当前类是一个自定义配置类,并添加为Spring容器的组件,这里也可以使用传统的@Component注解;
@Configuration
//指定了自定义配置文件的位置和名称,此示例表示自定义配置文件为classpath类路径下的test.properties文件
@PropertySource("classpath:test.properties")
@EnableConfigurationProperties(MyProperties.class) // 开启对应配置类的属性注入功能
//将上述自定义配置文件test.properties中以test开头的属性值注入到该配置类属性中。
@ConfigurationProperties(prefix = "test")
public class MyProperties {
private int id;
private String name;
// 省略属性getXX()和setXX()方法
// 省略toString()方法
}
如果配置类上使用的是@Component注解而非@Configuration注解,那么@EnableConfigurationProperties注解还可以省略。
@EnableConfigurationProperties
使ConfigurationProperties注解生效,并且将该类注入到 IOC 容器中,交由 IOC 容器进行管理。
如果一个配置类只配置@ConfigurationProperties注解,而没有使用@Component,那么在IOC容器中是获取不到properties 配置文件转化的bean。
用@EnableConfigurationProperties注解使@ConfigurationProperties生效,并从IOC容器中获取bean。
@ImportResource
自定义的xml配置文件,默认不会加载到Spring容器中来的。可使用@ImportResource注解将配置文件加载进来。
区别
@PropertySource | @ImportResource | |
使用位置 | 一般用在javabean的类名上 | 一般用于启动类上 |
引入文件类型 | *.properties或 *.yml | *.xml |