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

在项目中,有些参数需要配置到属性文件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

config.properties (示例属性)

admin_id=1
default_password=888888

ConfigInfo (对应的配置bean)

package com.jykj.demo.util;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public 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无法注入

使用

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

这个虽然简单,但我花了很久的时间从网上找寻各种解决方案,所以有必要写下来,这样可以方便以后尽快找到答案不要浪费时间。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值