spring 获取配置文件的键值对

使用

image.png




    
    
    
        
    

    
    
        
            
                classpath:server.properties
                classpath:weixin.properties
            
        
    

    

    



package component.common.utils;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;

/**
 * 扩展PropertyPlaceholderConfigurer,方便读取属性
* 使用方法: *
 * {@literal
 * 
 * 
 * 
 * classpath:/config.properties
 * 
 * 
 *
 * 然后调用PropertyUtil.getProperty(key);即可读取属性文件中的内容了
 *
 * }
 * 
* * @author tanghc */ public class PropertyUtil extends PropertyPlaceholderConfigurer { private static Map propertiesData = new HashMap(); @Override protected String convertProperty(String propertyName, String propertyValue) { String value = super.convertProperty(propertyName, propertyValue); propertiesData.put(propertyName, value); return value; } /** * 获取Properties文件中的值,如果不存在则返回defaultValue * * @param key * @param defaultValue * @return */ public static String getProperty(String key, String defaultValue) { String value = propertiesData.get(key); return value == null ? defaultValue : value; } /** * 获取Properties文件中的值,不存在返回null * * @param key * @return */ public static String getProperty(String key) { return getProperty(key, null); } }

(1)Controller 中 通过@value 读取properties配置信息

1、springmvc-servlet.xml 中配置:


    
    
        
            
                
                classpath:config.properties
            
        
    
    
        
    

2、basicmanagement.properties中配置参数

sessionTimeOut = 60  

3、Controller 获取方式

@Value("#{configProperties['sessionTimeOut']}")  
private int sessionTimeOut;  

(二)Service 中 通过@value 读取properties配置信息

1、applicationContext.xml中的配置

  
      
 

第二种方式

 
    

你可能感兴趣的:(spring 获取配置文件的键值对)