Spring用代码来读取properties文件实例解析

网友投稿 410 2023-02-27


Spring用代码来读取properties文件实例解析

有些时候,我们需要以Spring代码直接读取properties配置文件,那么我们要如何操作呢?下面我们来看看具体内容。

我们都知道,Spring可以@Value的方式读取properties中的值,只需要在配置文件中配置

org.springframework.beans.factory.config.PropertyPlaceholderConfigurer

classpath:config.properties

那么在需要用到这些获取properties中值的时候,可以这样使用

@Value("${sql.name}")

private String sqlName;

但是这有一个问题,我每用一次配置文件中的值,就要声明一个局部变量。有没有用代码的方式,直接读取配置文件中的值。

答案就是重写PropertyPlaceholderConfigurer

public class PropertyPlaceholder extends PropertyPlaceholderConfigurer {

private static Map propertyMap;

@Override

protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props) throws BeansException {

super.processProperties(beanFactoryToProcess, props);

propertyMap = new HashMap();

for (Object key : props.keySet()) {

String keyStr = key.toString();

String value = props.getProperty(keyStr);

prohttp://pertyMap.put(keyStr, value);

}

}

//static method for accessing context properties

public static Object getProperty(String name) {

return propertyMap.get(name);

}

}

在配置文件中,用上面的类,代替PropertyPlaceholderConfigurer

classpath:config.properties

这样在代码中就可以直接用编程方式获取

PropertyPlaceholder.getProperty("sql.name");

如果是多个配置文件,配置locations属性

class="com.gyoung.mybatis.util.PropertyPlaceholder">

file:./jdbc.properties

file:./module.config.properties

classpath:jdbc.properties

classpath*:*.config.properties

class="com.gyoung.mybatis.util.PropertyPlaceholder">

file:./jdbc.properties

file:./module.config.properties

classpath:jdbc.properties

classpath*:*.config.properties

总结

以上就是本文关于Spring用代码来读取properties文件实例解析的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站:

Spring实例化bean过程解析及完整代码示例

Spring工厂方法创建(实例化)bean实例代码

如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:详解SpringCloud微服务架构之Hystrix断路器
下一篇:微信小程序实现图片上传功能实例(前端+PHP后端)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~