Spring MVC 属性文件读取注入到静态字段

来源:互联网 发布:新浪网的域名和ip地址 编辑:程序博客网 时间:2024/06/03 15:37

目录(?)[-]

  1. servlet-contextxml
  2. configproperties 示例属性
  3. ConfigInfo 对应的配置bean
  4. 使用
 

在项目中,有些参数需要配置到属性文件xxx.properties中,这样做是为了维护方便,如果需要变动只需修改属性文件,不需要重新编译项目就可以了,非常方便。

而为了使用起来方便,可以通过将属性值注入到类的静态字段中(static),这样就可以用className.fieldName的方式来获取了。

1.servlet-context.xml

 <!-- spring的属性加载器,加载properties文件中的属性 -->       <bean id="propertyConfigurer"          class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">          <property name="location" value="classpath:config.properties" />      </bean>       <context:component-scan base-package="com.jykj.demo.util" /> 

 

注意: 这里需要配置spring自动扫描的包名,该包下包含了需要被注解的类ConfigInfo

2. config.properties (示例属性)

admin_id=1default_password=888888

3.ConfigInfo (对应的配置bean)

package com.jykj.demo.util;import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Component;@Componentpublic class ConfigInfo {    public static int admin_id;    public static String default_password;    //属性配置文件    @Value("${admin_id}")    public void setAdmin_id(int admin_id) {        ConfigInfo.admin_id = admin_id;    }    @Value("${default_password}")    public void setDefault_password(String default_password) {        ConfigInfo.default_password = default_password;    }}

 

注意: 这里需要将自动生成setter的方法的修饰符static去掉,否则spring无法注入

4. 使用

在任何类中直接使用 ConfigInfo.xxx 即可方便引用,如 ConfigInfo.default_password

原创粉丝点击