[英]inject stateless bean into a singleton bean
I have this requirement: I have a singleton bean and I have a method annotated with @PostConstruct where I perform some initialization. 我有这个要求:我有一个单例bean,并且有一个用@PostConstruct注释的方法,在其中执行一些初始化。 One of the initialization is to read some values from a DB, so I want to inject in this method a Stateless bean which is a service bean that access the DB.
初始化之一是从数据库读取一些值,因此我想在此方法中注入无状态Bean,该无状态Bean是访问数据库的服务Bean。 I don't want to inject the stateless bean as a field in the singleton bean because it is needed only in this method (nowhere else in the singleton bean).
我不想将无状态bean作为字段注入到singleton bean中,因为仅在此方法中才需要(在singleton bean中没有其他地方)。 To do so I did wrote this in singleton bean:
为此,我确实在单例bean中编写了此代码:
@Singleton
public class MySingletonBean {
@PostConstruct
@EJB
public void init(SLSBService service) { /* use service to read from DB */ };
...
}
The problem is that the Singleton bean can not be instantiated. 问题在于无法实例化Singleton bean。 Any idea?
任何想法? Thank you in advance.
先感谢您。
As the @PostConstruct annotated (callback) method is actually called after all references are resolved (all beans injected) I do not think this construct works. 由于在解析所有引用(注入所有bean)之后实际上会调用@PostConstruct带注释的(回调)方法,所以我认为此构造无效。
What you could do or try out is to remove the @PostConstruct and using normal setter injection. 您可以执行或尝试的操作是删除@PostConstruct并使用常规的setter注入。 However, be aware that other injected resources have not necessarily been resolved at this time.
但是,请注意,此时不一定已解决其他注入的资源。
@EJB
public void setService(SLSBService service){
service.doSmg();
}
@Stateless
public class SLSBService{
@PersistenceContext
private EntityManager em;
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public void doSmg() {
Member member = new Member();
member.setEmail("bla@bla.de");
member.setName("fubu");
member.setPhoneNumber("453454534535");
em.persist(member);
}
}
/* edit */ / *编辑* /
Just had some time for trying it out. 只是有一些时间来尝试。 The construct should be usable for DAOs, as the method is executed within a transaction and also the EntityManager (within the SLBService) is injected properly.
该构造应该可用于DAO,因为该方法在事务内执行,并且EntityManager(在SLBService内)也已正确注入。 And as expected references to other EJBs have not be resolved yet, so be aware of that.
而且,正如预期的那样,尚未解决对其他EJB的引用,因此请注意。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.