开发者

Spring - "late binding" autowired beans

开发者 https://www.devze.com 2023-03-24 18:16 出处:网络
Let\'s say I have the following dependencies: @Configuration public class MyCfg { // ... @Bean public Session session() {

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?


I would take a look at this bit of Spring documentation regarding bean scopes. Near the bottom they show how to use the @Scope annotation, which you will want to apply to your session() method in MyCfg. It sounds like you would want to use the 'request' value, which will create a new instance of this bean for each HTTP request coming in.

I will also suggest taking a look at the <aop:scoped-proxy/> element for configuration. It is mentioned a couple times in the documentation, and may be useful for what you are trying to do.


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 the SessionFactory instead. Instances of Session acquired within a @Transactional annotated method will adhere to those transaction rules, eg:

@Transactional(readonly=true)
public List<Person> getPersons() {
  Session session = sessionFactory.getCurrentSession();
  //find those darn people.
}
@Autowired
private SessionFactory sessionFactory; 
0

精彩评论

暂无评论...
验证码 换一张
取 消