咋一看,这两个注解给我的感觉就是有着剪不断理还乱七颠八倒横七竖八 的关系。
说一说这两个的运用场景:
@ConfigurationPropertie:
比如有个配置文件config.properties文件
config.name=test_name
config.other=test_other
我们想将这些配置信息从配置文件中读出来,映射到实体中,我们可以使用@ConfigurationPropertie。
在普通类上增加@ConfigurationProperties注解,可以获取该配置文件的内容
要注意的是:
1)当我们想将映射后的实体作为一个bean进行注入时候,需要增加@Component注解,从而与@ConfigurationPropertie相辅相成。
2)若配置文件不是默认配置文件(application.properties和application.yml)或路径不是默认路径的话,则需要通过@PropertySource注解在表明配置文件地址。
3)属性值需要getter setter方法,才能进行配置信息的映射和获取。
4)通过prefix可设置前缀,属性名定位前缀后的那部分,则可以直接获取到属性值。
// example:
//举个例子,要获取config.properties里config开头的两个配置config.name和config.other, 我们可以通过下面的代码方式映射。
//与此同时,还希望在其他bean中引用该实体,通过@Component注解进行Bean的注入,即可通过@Autowire进行该实体bean的获取
@ConfigurationProperties(prefix="config")
@Component
@PropertySource("classpath:/config.properties")
public Class Config{
private String name;
private String other;
// getter setter
}
最后在启动类上加入@EnableConfigurationProperties注解,用于将@ConfigurationProperties修饰的Bean生效。
@Configuration:
@Configuration同样可以实现将配置文件的信息映射到类中,但它更加有意义的功能,在于他能实现<beans>的功能,也就是可以在其中通过@Bean注解来注入多个Bean到IOC容器中。
// 实现将config.properties配置文件里的config.name和config.other属性进行获取的功能
@Configuration
@PropertySource("classpath:/config.properties")
public Class Config{
@Value("${config.name}")
private String name;
@Value("${config.other}")
private String other;
}
那么是如何实现注入多个Bean到IOC容器中呢:
@Configuration
public class ExampleConfiguration {
// 获取到application.properties里的com.mysql.jdbc.Driver配置项
@Value("com.mysql.jdbc.Driver")
private String driverClassName;
@Value("jdbc://xxxx.xx.xxx/xx")
private String driverUrl;
@Value("${root}")
private String driverUsername;
@Value("123456")
private String driverPassword;
//通过@Configuration和@Bean注解,将注入一个名称为dataSource的Bean,这个Bean的主体,便是dataSource()这个方法的结果
@Bean(name = "dataSource")
public DataSource dataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(driverClassName);
dataSource.setUrl(driverUrl);
dataSource.setUsername(driverUsername);
dataSource.setPassword(driverPassword);
return dataSource;
}
// 还能再继续注入其他的Bean
@Bean
public PlatformTransactionManager transactionManager() {
return new DataSourceTransactionManager(dataSource());
}
}
之后在需要使用该Bean的地方,便可以使用
@Autowired
private DataSource dataSource;
来注入,并使用
可以注意到,@Configuration比起@ConfigurationProperties ,在运用过程中,是不需要增加@Componet注解的,这是因为@Configuration这个注解本身已经增加了@Component注解,所以是不需要重复增加的。
@Configuration的功能更丰富些,主要运用在需要注入自定义Bean的场景下、
如果只是单纯作为获取配置信息用处,不注入bean的话,可以不使用@Configuration,直接使用@ConfigurationProperties来进行注入,同时一样使用@Value来获取即可,会更加直观些。
閱讀更多 居家程序員 的文章
關鍵字: 获取 properties private