Search code examples
javaspringstaticsingletonjavabeans

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?


Solution

  • 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.