简体   繁体   中英

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 with 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 (eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM