1. 程式人生 > >幾種配置properties檔案方法--SSM框架-附原始碼

幾種配置properties檔案方法--SSM框架-附原始碼

背景:  Spring、SpringMVC4.0.2、Mybatis3.2.6、JDK1.8、tomcat8、maven3.3.9、MyEclipse2013

專案結構:  

demo.properties: 

方法一: springmvc.xml  context:property-placeholder標籤引入

<context:component-scan base-package="com" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
<context:property-placeholder location="classpath:demo.properties" ignore-unresolvable="true"/>

注意: 若加上紅色部分,只能在controller注入service無法注入,反之controller、service均能注入

controller、service注入寫法一致

@Controller
@RequestMapping("/demo")
public class DemoController {
	
	@Autowired
	UserService userService;
	
	@Value("${demo.user}")
	private String user;
}

方法二: <bean id="propertyConfigurer"  
  class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  注入

<bean id="propertyConfigurer"  
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
        <property name="ignoreUnresolvablePlaceholders" value="true"/>
        	<!-- 引入properties配置檔案 方式一 -->
 		<property name="locations"> 
 		    <list> 
 		       <value>classpath:jdbc.properties</value> 
 		       <value>classpath:demo.properties</value>
 		    </list> 
 		</property>
</bean>  

注意: class注入寫法如方法一

方法三:  仿方法二,class自定義 。service層可直接註解取值

 <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
        <property name="ignoreUnresolvablePlaceholders" value="true"/>
         <property name="location" value="classpath:jdbc.properties" />
    </bean>
    <bean id="propertyConfigurer2" class="com.prop.PropertyConfigurer">  
        <property name="ignoreUnresolvablePlaceholders" value="true"/>
         <property name="locations">
	       <list>
	          <value>classpath:demo.properties</value>
	       </list>
        </property>
    </bean>

PropertyConfigurer.class

package com.prop;

import java.util.Properties;

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

public class PropertyConfigurer extends PropertyPlaceholderConfigurer {
	
	private Properties props;

    @Override
    protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props)
                            throws BeansException {
        super.processProperties(beanFactoryToProcess, props);
        this.props = props;
    }

    public String getProperty(String key){
        return this.props.getProperty(key);
    }

    public String getProperty(String key, String defaultValue) {
        return this.props.getProperty(key, defaultValue);
    }

    public Object setProperty(String key, String value) {
        return this.props.setProperty(key, value);
    }
}

controller:  @autowire注入bean   getProperty(key)取值

@Controller
@RequestMapping("/demo")
public class DemoController {

	@Autowired
	PropertyConfigurer prop;


        @RequestMapping("/list")
	public ModelAndView list(){
		
		String user = prop.getProperty("demo.user");
		System.out.println("controller user: " + user);
     ......

service:

@Service("userService")
public class UserService {
	
	@Autowired
	UserDao userDao;
	
	@Value("${demo.user}")
	private String user;

 

方法四: @PropertySource    @autowire注入Environment 

@Controller
@RequestMapping("/demo")
@PropertySource(value={"classpath:demo.properties"})
public class DemoController {
	@Autowired
    private Environment environment;
	
	@RequestMapping("/list")
	public ModelAndView list(){
		String user = environment.getProperty("demo.user");
		System.out.println("controller user: " + user);
        .......

方法五: <bean id="demoProp" class="org.springframework.beans.factory.config.PropertiesFactoryBean">  bean注入

 class檔案注入方式@Value(value="#{demoProp[demo_user]}")

需要注意的是,PropertiesFactoryBean實現了 FactoryBean<Properties>,用的是Properties.class解析配置檔案。

所以當properties檔案中用小數點"."命名key時(如demo.user),class注入時需把key加上單引號(#{demoProp['demo.user']

    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
         <property name="ignoreUnresolvablePlaceholders" value="true"/>
          <property name="location" value="classpath:jdbc.properties" />
    </bean>
     
   <bean id="demoProp" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
          <property name="locations">
              <list>
                  <value>classpath:demo.properties</value>
              </list>
           </property>
           <!-- 設定編碼格式 -->
           <property name="fileEncoding" value="UTF-8"></property>
    </bean>

或者

<bean id="demoProp" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
        <property name="locations">
            <list>
                <value>classpath:demo.properties</value>
                <value>classpath:jdbc.properties</value>
            </list>
        </property>
        <!-- 設定編碼格式 -->
        <property name="fileEncoding" value="UTF-8"></property>
    </bean>
    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
        <property name="ignoreUnresolvablePlaceholders" value="true"/>
        <property name="properties" ref="demoProp" />
    </bean>

上述寫法既可用#{demoProp[demo_user]} ,亦可用${demo_user}

方法六: <util:properties />注入

需在xml檔案加上 xmlns:util="http://www.springframework.org/schema/util"

                            xsi:schemaLocation=http://www.springframework.org/schema/util 

                                                              classpath:/org/springframework/beans/factory/xml/spring-util-4.0.xsd

在此說明下,由於是在myeclipse下,彈出安全證書點了否,查詢半天資料引入本地xsd檔案 /捂臉/捂臉/捂臉

附上網路版 http://www.springframework.org/schema/util/spring-util-4.0.xsd

<util:properties id="demoProp" location="classpath:demo.properties"/>

注意: 注入方式參考方法五

方法七: utils.class讀取配置檔案

public class PropertiesUtils {
	private static final Logger logger = LoggerFactory.getLogger(PropertiesUtils.class);
	private static final String FILE_NAME = "demo.properties";
    private static Properties props;
    static{
        loadProps();
    }

    synchronized static private void loadProps(){
        logger.info("開始載入properties檔案內容.......");
        props = new Properties();
        InputStream in = null;
        try {
        	//第一種,通過類載入器進行獲取properties檔案流
//            in = PropertiesUtils.class.getClassLoader().getResourceAsStream(FILE_NAME);
            //第二種,通過類進行獲取properties檔案流
            in = PropertiesUtils.class.getResourceAsStream("/" + FILE_NAME);
            props.load(in);
        } catch (FileNotFoundException e) {
            logger.error(FILE_NAME + "檔案未找到");
        } catch (IOException e) {
            logger.error("出現IOException");
        } finally {
            try {
                if(null != in) {
                    in.close();
                }
            } catch (IOException e) {
                logger.error(FILE_NAME + "檔案流關閉出現異常");
            }
        }
        logger.info("載入properties檔案內容完成...........");
        logger.info("properties檔案內容:" + props);
    }

    public static String getProperty(String key){
        if(null == props) {
            loadProps();
        }
        return props.getProperty(key);
    }

    public static String getProperty(String key, String defaultValue) {
        if(null == props) {
            loadProps();
        }
        return props.getProperty(key, defaultValue);
    }
}

用法: 

String user = PropertiesUtils.getProperty("demo.user");

至此,所有方式記錄完畢。

原始碼下載地址: https://download.csdn.net/download/weixin_42803662/10680879

參考資料: 

        http://www.cnblogs.com/hafiz/p/5876243.html

        https://blog.csdn.net/h396071018/article/details/38333589