Question

@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?

Was it helpful?

Solution

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.

OTHER TIPS

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

You may try to use @Scope("session")

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top