spring 注入static属性
来源:互联网 发布:设计界面的软件 编辑:程序博客网 时间:2024/05/21 06:21
网上好多方法都是错误的,google之,发现
http://stackoverflow.com/questions/11324372/how-to-make-spring-inject-value-into-a-static-field 写道
You have two possibilities:
In the first option you have a bean with a regular setter but instead setting an instance property you set the static property/field.
publicvoid setTheProperty(Object value){ foo.bar.Class.STATIC_VALUE = value;}
but in order to do this you need to have an instance of a bean that will expose this setter (its more like anworkaround).
In the second case it would be done as follows:
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean"><property name="staticMethod" value="foo.bar.Class.setTheProperty"/><property name="arguments"><list><ref bean="theProperty"/></list></property></bean>
On you case you will add a new setter on the Utils
class:
publicstatic setDataBaseAttr(Properties p)
and in your context you will configure it with the approach exemplified above, more or less like:
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean"><property name="staticMethod" value="foo.bar.Utils.setDataBaseAttr"/><property name="arguments"><list><ref bean="dataBaseAttr"/></list></property></bean>
其中方法二 应该比较实用,就是配置xml,配置staticMethod,以及instance
也可以这么玩
http://stackoverflow.com/questions/7253694/spring-how-to-inject-a-value-to-static-field 写道
publicclassSample{publicstaticString name;@PostConstructpublicvoid init{ name = privateName;}@Value("${my.name}")privateString privateName;publicString getPrivateName{return privateName;}publicvoid setPrivateName(String privateName){this.privateName = privateName;}}
但是下面有大神说了 Firs of all, public static
non-final
fields areevil. Spring does not allow injecting to such fields for a reason.
because Non-final means you can modify the field value, which, for a static field, implies handling thread concurrency - a.k.a. pain in the stack.
本文为头条号作者发布,不代表今日头条立场。
- spring 注入static属性
- spring annotation 注入static 属性
- spring annotation 注入static 属性
- spring annotation 注入static 属性
- Spring注入static属性的方法
- spring拾遗(一)——@Value注入static属性
- spring注入static变量
- spring注入static变量
- spring @value 注入static
- spring 注入static 字段 @value
- spring 属性注入
- spring公共属性注入
- Spring中的属性注入
- Spring属性注入
- spring 注入属性
- Spring---->属性的注入
- Spring对象属性注入
- Spring属性注入
- 分享—SQL注入整理贴
- linux下redis和mongo常用命令
- js去除重复并统计数量方法
- GPU英伟达CUDA安装配置
- MySQL误操作后如何快速恢复数据?
- spring 注入static属性
- Android自定义ProgressDialog
- CButtonST使用技巧(一)
- ubuntu下opencv2.4.10 和 opencv 3.10 多版本切换问题
- MFC笔记:解决头文件相互包含带来的问题
- 大龄程序员的未来之我见
- svg中path标签的用法(转载)
- Redis安装与应用
- myeclipse----怎么配置要使用的jdk