• 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

    2. config.properties (示例属性)

    admin_id=1
    default_password=888888

    3.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无法注入

    4. 使用

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

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

     
     
  • 相关阅读:
    InstallShield 12 制作安装包
    php常用知识集锦
    Bootstrap是什么
    php实现简单的学生管理系统
    php实现邮箱激活功能
    php定界符<<<EOF讲解
    qq邮箱的SMTP服务器是什么
    mysqli一些常用方法及详解
    mysqli的简单工具包
    mysqli数据库操作简单实例
  • 原文地址:https://www.cnblogs.com/yhtboke/p/5749172.html
Copyright © 2020-2023  润新知