I have an old project that I need to integrate with Spring 2.5.x (3.0 is not possible).
I have created a bean, that have to initializate its field userSession by itself:
public class SomeBean {
UserSession userSession;
@PostContrust
public void init() {
HttpSession session = WebContext.current().getSession();
userSession = (UserSession) session.getAttribute("userSession");
}
}
Is it possible to write some kind of autowiring handler that will resolve userSession and pass it for autowiring to Spring, so my bean looks just like:
public class SomeBean {
@Autowire UserSession userSession;
}
and the handler like:
public class AutowireHanlder {
public boolean isCandidate(Class<?> type) {
return type.equals(UserSession.class);
}
public Object resolve(Class<?> type) {
HttpSession session = WebContext.current().getSession();
return (UserSession) session.getAttribute("userSession");
}
}
I would do this using a session-scoped
FactoryBean:Define
UserSessionFactoryBeanas a bean:… and then you should then be able to autowire
UserSessioninto any other bean.The complexity here is that
UserSessionFactoryBeanhas to be session-scoped (see docs on bean scopes), since it must return a new value for eachHttpSession. This means that any bean it is autowired into must also be session-scoped, otherwise it’ll fail. You can get around this restriction using scoped-proxies.