简体   繁体   中英

Should I use static at all in spring singleton beans

As I just read, by default my created spring beans are Singletons. I'm currently using the static keyword for my Loggers, reused variables, and some Lists that I want to exist only once.

But because alls beans are singletons I'm thinking about just removing static from everything.

private static final Logger LOGGER = LoggerFactory.getLogger(MatchmakingService.class);
private static final List<Lobby> QUEUE_BLOCKED = new ArrayList<>();

to

private final Logger logger = LoggerFactory.getLogger(MatchmakingService.class);
private final List<Lobby> queueBlocked = new ArrayList<>();

My question is, should I use "static" at all within the spring context? If yes, why?

Spring is designed so that for the vast majority of cases you can avoid static fields.

Having a logger that is static final is perfectly ok. Loggers are threadsafe and are designed to be used this way.

Having static final constants is ok.

Other than loggers, anything static that is not immutable should be avoided.

Also do not use instance variables for conversational state (state related to actions performed by callers of the service), because other callers can access and change that state.

If you are using instance or static variables to cache, get rid of them and configure a cache manager instead.

If your code is storing configuration data in static fields, make them instance fields and use spring to read the config data in.

Using a static logger within a class generally makes sense if it is logging to the same file or output stream (eg System.out ), regardless of which instance logs something. Whether the queue in your code snippit should be static or not depends on its use and cannot be answered without more details.

Good question. In my opinion, If you business scenario stay always in same spring context, you should not use static. The reason is that spring bean is single in one spring context。But bean has different instance in different spring context. The below is sample code:

//  The first Spring Bean Context
ApplicationContext context1 = new FileSystemXmlApplicationContext("classpath:/ApplicationContext.xml");
Biz b1 = context1.getBean("myBean", Biz.class);

//  The second Spring Bean Context
ApplicationContext context2 = new FileSystemXmlApplicationContext("classpath:/ApplicationContext.xml");
Biz b2 = context2.getBean("myBean", Biz.class);

//  The result is false, because of creating two instances of Biz
System.out.println(b1 == b2);

But static variable has one instance in one JVM. So for performance and robust,you should use static more often. In another word, you can not make all class as bean in a program.

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