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不推荐这样做。至于还有没有其他的什么原因,抱歉,没有搜到,咯咯,若你有什么好的理由,可以私聊哦,谢谢!

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM