Static Singleton Instance of Spring's ApplicationContext

2.4k views Asked by At

I'm trying to port an application written with CURAM to a Struts2 project. We are using Spring to take advantage of its database transaction capabilities. Do to the way application code is written in a CURAM application, I cannot use the Dependency Injection feature of Spring. I need to be able to access the Spring ApplicationContext from anywhere in my business logic. And creating a new instance of ApplicationContext whenever I need it grinds things down to a screeching halt.

I found this resource on the internet that shows you how to create a static singleton instance of Spring's ApplicationContext.

Access the Spring-ApplicationContext from everywhere in your Application

This would solve my issue, but I have concerns. Wouldn't a static singleton instance mean that every user invoking a Struts2 action would be getting business objects from the same ApplicationContext instance?

By default, Spring beans are singletons within an ApplicationContext instance. Because of this, I'm thinking that a static singleton instance of ApplicationContext would cause the same instance of all business objects to be used by all users / transactions, which would ruin transactions and probably cause locks all over the place. Am I correct in assuming this?

What if I declared all of my Spring Beans as prototype? Would that allow me to take advantage of Springs Database Transaction / Concurrency Handling capabilities while using a static-singleton instance of ApplicationContext?

Thanks.

2

There are 2 answers

2
JB Nizet On BEST ANSWER

Wouldn't a static singleton instance mean that every user invoking a Struts2 action would be getting business objects from the same ApplicationContext instance?

yes

I'm thinking that a static singleton instance of ApplicationContext would cause the same instance of all business objects to be used by all users / transactions

yes

which would ruin transactions and probably cause locks all over the place.

no. Why would that ruin transactions? Why would there be locks? A business service is typcically completely stateless, and is thus fine as a singleton. A typical Spring application only has a single application context, containing singleton beans. That's how it's designed to work. The transaction context isn't stored in the business objects. It's stored in a ThreadLocal.

0
Mikhail On

if you create a class without common variables, using siglton it will be the best choise. you can @Autowired necessary сlass likes Dao or Services class

if your class will be prototype and you get the Bean from Applicationcontext every time it will be a new object