Let’s say I have the following dependencies:
@Configuration
public class MyCfg {
// ...
@Bean
public Session session() {
return sessionFactory().getCurrentSession();
}
}
@Repository
@Transactional
public class MyRepo {
@Autowired
private Session session;
}
sessionFactory() is set up properly. If I inject SessionFactory instead of Session, it works just fine. However, if try and inject Session, it dies with an exception on container bootstrap because there is no session bound to thread.
Since the repository is @Transactional, I know that at run time there will be a session. How can I make it work, so that it injects AOP-initialized Session at run time, but does not try and resolve it when the repo is instantiated?
This approach will get you into a lot of trouble. Instead of injecting a
Session, which you now automatically scopes as a singleton, you should inject theSessionFactoryinstead. Instances ofSessionacquired within a@Transactionalannotated method will adhere to those transaction rules, eg: