There is some way to use @Autowired with static fields. Or there are some other ways to do this?
A:
In short, no. You cannot autowire or manually wire static fields in Spring. You'll have to write your own logic to do this.
skaffman
2009-06-19 17:13:28
A:
Create a bean which you can autowire which will initialize the static variable as a side effect.
Jherico
2009-06-20 01:21:49
+1
A:
@Autowired
can be used with setters so you could have a setter modifying an static field.
Just one final suggestion... DON'T
victor hugo
2009-06-20 01:27:07
Clever.... I can't bring myself to upvote that, though :)
skaffman
2009-06-21 14:43:05
A:
You can achieve this using XML notation.
private static StaticBean staticBean;
public void setStaticBean(StaticBean staticBean) {
StaticBean.staticBean = staticBean;
}
You should aim to use spring injection where possible as this is the recommended approach but this is not always possible as I'm sure you can imagine as not everything can be pulled from the spring container or you maybe dealing with legacy systems.
Note testing can also be more difficult with this approach.
JamesC
2009-06-22 09:37:59