[关闭]
@MrXiao 2017-12-19T03:45:22.000000Z 字数 2762 阅读 1001

Java中读取properties

Spring Properties


将一些业务常量配置成properties文件,是扩展程序兼容性的常用做法。在业务变更导致数据需要改变时,不需要修改代码,只用更改配置文件并重启即可生效。

方法一:IO实现

  1. public static String getValue(String fileNamePath, String key) throws IOException {
  2. Properties props = new Properties();
  3. InputStream in = null;
  4. try {
  5. in = new FileInputStream(fileNamePath);
  6. //如果将in改为下面的方法,必须要将.Properties文件和此class类文件放在同一个包中
  7. //in = propertiesTools.class.getResourceAsStream(fileNamePath);
  8. props.load(in);
  9. String value = props.getProperty(key);
  10. // 有乱码时要进行重新编码
  11. // new String(props.getProperty("name").getBytes("ISO-8859-1"), "GBK");
  12. return value;
  13. } catch (FileNotFoundException e) {
  14. return null;
  15. } finally {
  16. if (null != in) {
  17. in.close();
  18. }
  19. }
  20. }

方法二:spring实现

在spring扫描配置文件时,将properties中的key和value放入一个map中。

  1. Spring配置

    1. <bean id="propertyConfigurer" class="com.hapishop.util.ProjectDBinfoConfigurer">
    2. <property name="locations">
    3. <list>
    4. <value>classpath*:/META-INF/*.properties</value>
    5. <value>file:conf/*.properties</value>
    6. </list>
    7. </property>
    8. </bean>
  2. 自定义CustomizedPropertyConfigurer,继承PropertyPlaceholderConfigurer

    1. public class CustomizedPropertyConfigurer extends PropertyPlaceholderConfigurer {
    2. private static Map<String, String> properties = new HashMap<String, String>();
    3. protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props) throws BeansException {
    4. // cache the properties
    5. PropertyPlaceholderHelper helper = new PropertyPlaceholderHelper(DEFAULT_PLACEHOLDER_PREFIX,DEFAULT_PLACEHOLDER_SUFFIX, DEFAULT_VALUE_SEPARATOR, false);
    6. for (Entry<Object, Object> entry : props.entrySet()) {
    7. String stringKey = String.valueOf(entry.getKey());
    8. String stringValue = String.valueOf(entry.getValue());
    9. stringValue = helper.replacePlaceholders(stringValue, props);
    10. properties.put(stringKey, stringValue);
    11. }
    12. super.processProperties(beanFactoryToProcess, props);
    13. }
    14. public static Map<String, String> getProperties() {
    15. return properties;
    16. }
    17. public static String getProperty(String key) {
    18. return properties.get(key);
    19. }
    20. }
  3. 配置properties

    1. site=iteye
    2. blog=antlove
    3. url=${site}/${blog}
  4. Java获取

    1. //调用此方法获取value
    2. CustomizedPropertyConfigurer.getContextProperty()

方法三:注解实现

spring加载properties的两个类的区别

在java 代码里,一般是使用@Value注解来引用 properties 文件的属性。

使用 PropertyPlaceholderConfigurer 时, @Value表达式的用法是 @Value(value="${properties key}") ,

使用 PropertiesFactoryBean 时,我们还可以用@Value 读取 properties对象的值, @Value 用法 是 @Value(value="#{configProperties['properties key']}")

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注