PropertiesFactoryBean的使用

來源:互聯網
上載者:User

使用Spring注入Properies檔案方法:

 

1、src中建立一個settings.properties檔案,內容如下:

db_driverClassName=com.mysql.jdbc.Driverdb_url=jdbc:mysql://127.0.0.1/testdb_username=rootdb_password=roottest_userName=Robintest_age=18

2、在spring的applicationContext.xml中加入這段:

    <bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">        <property name="locations">            <list>                <value>classpath*:settings.properties</value>            </list>        </property>    </bean>    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">        <property name="ignoreResourceNotFound" value="false" />        <property name="properties" ref="configProperties" />    </bean>

之後的spring的xml配置中可以直接這樣使用了:

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">        <property name="driverClassName" value="${db_driverClassName}"/>        <property name="url" value="${db_url}" />        <property name="username" value="${db_username}" />        <property name="password" value="${db_password}" />    </bean>

3、建立一個class:Settings.java

package com.my.common;import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Component;@Componentpublic class Settings {    private static Settings instance;    public static Settings getInstance() {        return instance;    }    public Settings() {        instance = this;    }        @Value("#{configProperties['test_userName']}")    private String userName;    @Value("#{configProperties['test_age']}")    private int age;        public String getUserName() {        return userName;    }    public void setUserName(String userName) {        this.userName = userName;    }    public int getAge() {        return age;    }    public void setAge(int age) {        this.age = age;    }}

然後可以在代碼中這樣調用了:

Settings.getInstance().getUserName()

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.