当前位置 : 主页 > 编程语言 > c++ >

Spring容器加载自定义配置

来源:互联网 收集:自由互联 发布时间:2021-06-30
ProjectPropertyPlaceholderConfigurer.java import java.util.HashMap;import java.util.Map;import java.util.Properties;import org.springframework.beans.BeansException;import org.springframework.beans.factory.config.ConfigurableListableBeanFact
ProjectPropertyPlaceholderConfigurer.java
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

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

/**
 * 项目配置文件加载类
 * @author wuqx
 *
 */
public class ProjectPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer {
	
	 private static Map
 
   ctxPropertiesMap;

	@Override
	protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props)
			throws BeansException {
		super.processProperties(beanFactoryToProcess, props);
		
		ctxPropertiesMap = new HashMap
  
   (); for (Object key : props.keySet()) { String keyStr = key.toString(); String value = props.getProperty(keyStr); ctxPropertiesMap.put(keyStr, value); } } /** * 获取配置信息 * @param name * @return */ public Object getContextProperty(String name) { return ctxPropertiesMap.get(name); } }
  
 
ProjectPropertiesUtil.java
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component(value = "projectPropertiesUtil")
public class ProjectPropertiesUtil implements ApplicationContextAware {
	
	public static final String KEY = "propertyConfigurer";
	
	private static ApplicationContext applicationContext;

	@Override
	public void setApplicationContext(ApplicationContext context) throws BeansException {
		 applicationContext = context;
	}
	
	public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }
	
	/**
     * 获取配置文件中的内容
     *
     * @param keyName
     * @return
     */
    public String getProperty(String keyName) {
    	ProjectPropertyPlaceholderConfigurer configure = (ProjectPropertyPlaceholderConfigurer) applicationContext.getBean(KEY);
        return configure.getContextProperty(keyName).toString();
    }

}
网友评论