I have some Spring managed classes (through xml configuration), one of which is a SessionFactory, which is injected into another Spring managed class. Whenever this class needs a new Session it calls createSession on the SessionFactory.
However unless I’m mistaken this means that the Sessions themselves are not Spring managed, which is problematic as they have some @Transactional methods, which require the bean to be managed by Spring.
I’ve been reading up on FactoryBeans, but I’m not sure how the best way to do this is, especially as my createSession method takes a parameter, and the FactoryBean.getObject() does not.
I can use getObject and then set the parameter manually higher up, but I’d like to force the set in the factory if possible.
Can anyone help? Thanks in advance. A simplified example is below.
public class SessionFactory {
public final Session createSession(String username){
Session session = new SessionImpl(username);
return session;
}
}
public class SessionImpl implements Session{
private String username;
@Override
@Transactional
public void doSomething(){
// Does something
}
public void setUsername(String username){
this.username = username;
}
public String getUsername(){
return username;
}
}
public class Service {
private SessionFactory sessionFactory; // Set by Spring through xml config
public void doSomethingServicy(){
}
public void setSessionFactory(SessionFactory sessionFactory){
this.sessionFactory = sessionFactory;
}
}
I solved it by creating the factory bean in Spring, and declaraing a prototype-scoped Session object with a factory bean and factory method as seen below:
Then retrieving a new instance in the code when required:
Here username is part of the
Object...method parameter which makes up the arguments that get passed into the factoriescreateSessionmethodI appreciate the structure of the program could be better, but given the restrictions on the code it solves the problem nicely.