java 注解properties文件_Spring Java 注解配置之 properties文件注入

全局配置文件注入

由于Spring存在2个应用上下文,一个是WebApplicationContext,另一个是ServletApplicationContextInitializer。它们两者之间有的bean实例是不通用的。比如本文要使用PropertyPlaceholderConfigurer类实例。

第一步、配置文件扫描

将properties文件都放在classpath下,可以自定义目录。例如我就放在了resources/config目录下,主要是为了自己方便查找。

38b1b4a5277a

image.png

使用PropertiesFactoryBean扫描全部的properties文件。

/** 加载配置文件 */

@Bean("propertiesBean")

public PropertiesFactoryBean propertiesFactoryBean() throws IOException {

PropertiesFactoryBean factoryBean = new PropertiesFactoryBean();

factoryBean.setLocations(ResourceUtil.getResources("classpath:config/*.properties"));

return factoryBean;

}

其中ResourceUtil是自己根据PathMatchingResourcePatternResolver封装的一个工具类,主要是为了代码整洁。源码如下:

public class ResourceUtil {

public static Resource getResource(String location) {

return resolver().getResource(location);

}

public static Resource[] getResources(String locationPattern) throws IOException {

return resolver().getResources(locationPattern);

}

public static PathMatchingResourcePatternResolver resolver() {

return new PathMatchingResourcePatternResolver();

}

}

第二步、将配置注入应用上下文

使用PropertyPlaceholderConfigurer将配置内容注入上下文,该bean必须是static方法,否则启动会异常告警。

由于开始说了spring mvc 存在2个应用上下文,所以在使用该类进行配置注入的时候需要分别在ServletRootConfig.class和ServletWebConfig.class中都要写上该方法。

/** 注入配置文件 */

@Bean("propertyPlaceholderConfigurer")

public static PropertyPlaceholderConfigurer propertyPlaceholderConfigurer(@Qualifier("propertiesBean") Properties properties) throws IOException {

PropertyPlaceholderConfigurer configurer = new PropertyPlaceholderConfigurer();

configurer.setProperties(properties);

return configurer;

}

第三步、使用配置内容

有了以上配置后,你就可以在 Service、Controller 等任意bean中使用@Value注解注入properties文件的配置了。

eg:

@Value("${value}")

private String value;

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值