views:

368

answers:

2

@Autowired works only once.

What to do to make it wire the bean every time the Servlet is recreated?

My web-app (Tomcat6 container) consists of 2 Servlets. Every servlet has private fields.

Their setters are marked with @Autowired

In the init method I use

WebApplicationContextUtils
...
autowireBean(this);

It autowires the properties marked with @Autowired once - during the initialization of the Servlet.

Any other session will see these fields values, they will not be rewired after the previous session is destroyed.

What to do to make them rewire them each time a Servlet constructor is called?

a) Put the autowiring into the constructor?

Or better 2) get a web app context and extract a bean from there?

+1  A: 

Try using scope as prototype for that bean @Scope("prototype")

Teja Kantamneni
this will force spirng to produce a new bean each time one is needed
c0mrade
That will tell Spring to make a new one when getBean is invoked; however, a servlet is still a servlet. Marking a bean prototype doesn't summon up black magic that will make the servlet container create a new servlet for each web thread. It will still just make the one.
Affe
@Affe agreed. I missed the point there. But it may be done using the method injection or making it baenfactoryaware and every time before using the object get a new instance from the factory will solve it.
Teja Kantamneni
+1  A: 

There seems to be some misunderstanding about how the container works. Servlets are essentially singletons, you don't get a new servlet everytime someone calls the server. Storing state in private fields on a servlet is pretty much an error.

What is the scope and life-cycle of the stateful part of your request processing? If it's just the life of the request then you can take whatever on your servlet is stateful and move it into another class. Then you can define a prototype bean for that class and use getBean at the start of the request to get a new one. If you want to start getting fancy you could write a filter that puts a new bean into a ThreadLocal at the start of each request.

If your state needs to span multiple requests, you need to start keeping state or a key that points to the state storage on the web session, or look into using a conversation framework.

Affe