zoukankan      html  css  js  c++  java
  • Spring 注入static变量

    一般我们我想注入一个static的变量,如下:

        @Autowired
        private static String str;

    不过,这样最终结果为null

    1、使用配置文件的方式注入

      

     private static String from;
    
        public static String getFrom() {
            return from;
        }
    
        public static void setFrom(String from) {
            TestStatic.from = from;
        }
    
    
        <bean class="TestStatic">
            <property name="from" value="abc"/>
        </bean>

    2、使用注解的方式,不过注解写在非static的方法上

        private static String to;
        
        public static String getTo() {
            return to;
        }
        
        @Value("${mail.to}")
        public void setTo(String to) {
            TestStatic.to = to;
        }

    备注:目前Spring的注解不支持静态的变量和方法,至于原因:有人说是因为Spring是基于对象层面的依赖注入的,而且使用静态的变量或类什么的话,扩大了其生命周期,给Testing带来困难,故Spring不推荐这样做。至于还有没有其他的什么原因,抱歉,没有搜到,咯咯,若你有什么好的理由,可以私聊哦,谢谢!

  • 相关阅读:
    uoj110
    11.28模拟赛D题解
    AT1219 歴史の研究
    P5906 【模板】回滚莫队&不删除莫队
    P4175 [CTSC2008]网络管理
    SP32952 ADAFTBLL
    CF1479D Odd Mineral Resource
    SP10707 COT2
    P4074 [WC2013] 糖果公园
    P6134 [JSOI2015]最小表示
  • 原文地址:https://www.cnblogs.com/xiaoxian1369/p/4654481.html
Copyright © 2011-2022 走看看