开发者

Effect of declaring a singleton Spring bean static?

If you have

private static MyDAO myDAO;

And declared in applicationContext as

<bean id="myDAO" scope="singleton" class="my.MyDAO" />

Is there any effect on declaring myDAO wit开发者_C百科h the static modifier when it is already declared as singleton?

Thanks in advance!


The bean declaration means that the Spring IoC system will create only one instance (per webapp) of your my.MyDOA object. But there is nothing stopping other things (e.g. your code) from creating other instances.

If you are populating the myDAO variable via Spring IoC (using wiring files or annotations) then there is no need for it to be declared as static. If there are multiple instances of the class containing that declaration, and the instances are created / wired by Spring IoC, then all copies of the variable will get the same value. Declaring it static is pointless and bad style.

On the other hand, if your application is creating instance of the class containing that declaration, then it will need to take appropriate steps to initialize it. And your method of initializing the variable will depend on whether or not the variable is static. You probably don't want to do this ...


Remove static. When working with spring beans forget about static when it comes to dependencies.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜