Spring 如何给static变量赋值

来源:互联网 发布:json汉字 编辑:程序博客网 时间:2024/06/06 02:21

        先说明如何在将配置文件中的值赋值给spring中的变量:

               1.在classpath下面的.properties文件中定义变量;

               2.在spring配置文件中将.properties加载进来:    <context:property-placeholder ignore-unresolvable="true" location="classpath:*.properties"/>

               3.在需要赋值的java变量上加注解:@Value("${properties文件中的key}")


        然后就有坑了,spring这样可以给变量赋值,但是该变量必须是非static的,因为static修饰的变量在类加载的时候就加载了。这个时候如果断点调试,可以发现他是null,那么如何给一个static变量赋值呢,其实就是通过非静态变量赋值,即先给非static修饰的赋值,在将这个值赋值给static变量。我们可以通过set方法,注意这个方法必须是非静态的方法。

@Component

class Test{

           public static String COUPON_RECEIVEE; // 当前应用 环境
    
        @Value("${coupon_receivee}")
        public  void setTest(String coupon_receivee) {
          UrlConstants.COUPON_RECEIVEE = coupon_receivee;
        }

}

原创粉丝点击