使用spring加载properties文件

  • 在spring的配置文件中,配置如下:

<bean id="propertyConfigurer" class="com.common.PropertiesBean">
		<property name="locations">
			<list>
				<value>classpath:sysconf.properties</value>
				<value>classpath:db-config.properties</value>
				<value>classpath:security-config.properties</value>
				<value>classpath:source.properties</value>
			</list>
		</property>
</bean>

  • 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");
%>

猜你喜欢

转载自lsz1023-126-com.iteye.com/blog/2326273