K
K
Kirill2011-12-27 00:30:58
Java
Kirill, 2011-12-27 00:30:58

How to store shared data in Spring?

I just can't figure out if it's okay to store common objects for all users in the static variables of the Spring controller class?
For example, you need to implement a chat for the last 5 messages without a database and files. If you create an ArrayList and a method for adding a message to it, then everything seems to work.
But is this approach normal? It won't cause multithreading collisions like it would if it wasn't in Spring?
Or maybe there are other ways to store already constructed objects for public use? The task is to store exactly instances of classes that take a long time to create, but are needed every time the user enters.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
serso, 2011-12-27
@serso

No, it's not normal (and indeed in Spring to store something statically - the height of madness - with its Dependency Injection).
What you are doing is called data caching. It can be different depending on the goals, in your case it is at the application level (i.e. one cache instance for the entire application). As far as I remember, Spring has a mechanism for declaring a bean (bean), while it is possible to set its scope. So here is your case - singleton or (if there is of course) application bean.
Concerning a multithreading - a natural problem of general resources. Here, unfortunately, Spring will not help you either - you need to implement it yourself using the synchronized construct.

J
javax, 2011-12-27
@javax

This is bad. If you have two application context instances (for example, 2 web applications on the same server, or during unit tests) - this cache will be shared.
Make another singleton bean that will store this data

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question