以@Value方式注入 properties 配置文件

类中读取XML文件不是太方便,所以使用*.properties是比较好的办法

注入方式获取是最直接,最快捷的。这个操作主要涉三个部分,下面分别介绍:

首先,配置文件准备。这里文件名命名为application.properties:

#Updated at Tue Aug 13 14:45:50 CST 2014
#Tue Aug 13 14:45:50 CST 2014
cpuid=0

其次,XML文件准备。beans.xml文件中添加如下:

    <bean id="configProperties"
        class="org.springframework.beans.factory.config.PropertiesFactoryBean">
        <property name="locations" value="/WEB-INF/spring/application.properties">
        <!--WEB-INT下面的配置文件的路径-->
        </property>
    </bean>
    <bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
        <property name="properties" ref="configProperties" />
    </bean>

最后,注入到@Controller 类中添加如下属性获取配置文件的值。

 @Value("#{configProperties['cpuid']}")//configProperties为XML文件中所配置的id
    private String myID;
    public String getMyID() {
        return myID;
    }

    public void setMyID(String myID) {
        this.myID = myID;
    }

注入后的myID不需要赋值,可以直接获取cpuid的值。

原文地址:https://www.cnblogs.com/Weagle/p/4368340.html