使用spring加载properties文件

阅读更多
  • 在spring的配置文件中,配置如下:


		
			
				classpath:sysconf.properties
				classpath:db-config.properties
				classpath:security-config.properties
				classpath:source.properties
			
		


  • com.common.PropertiesBean实现此类

package com.common;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import com.util.LifeCycleManage;

public class PropertiesBean extends PropertyPlaceholderConfigurer
{
    private static final Logger LOG = LoggerFactory.getLogger(PropertiesBean.class);
    
    @Override
    protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props)
        throws BeansException
    {
	    // LifeCycleManage 需要自己实现,单例模式
        LifeCycleManage.setProperty(props);
        super.processProperties(beanFactoryToProcess, props);
    }
}

  • 添加一个单例模式的读取配置累

package com.util;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LifeCycleManage
{
    private static final Logger LOGGER = LoggerFactory.getLogger(LifeCycleManage.class);
    private static Properties propertyConfigurer;
    public static void setProperty(Properties ipropertyConfigurer)
    {
        propertyConfigurer = ipropertyConfigurer;
    }
    public static String getProperty(String proName)
    {
        String str = "";
        if (propertyConfigurer == null)
        {
            return str;
        }
        str = propertyConfigurer.getProperty(proName);
        return str;
    }
    
}

  • 然后就可以到java类中、jsp的小脚本中使用了

String servicename = LifeCycleManage.getProperty( "servicename");

<%@page import="com.util.LifeCycleManage" %>
<%
    String servicename = LifeCycleManage.getProperty( "servicename");
	String version = LifeCycleManage.getProperty( "version");
%>

你可能感兴趣的:(使用spring加载properties文件)