Domanda

I have this requirement: I have a singleton bean and I have a method annotated with @PostConstruct where I perform some initialization. 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. 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). To do so I did wrote this in singleton 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. Any idea? Thank you in advance.

È stato utile?

Soluzione

As the @PostConstruct annotated (callback) method is actually called after all references are resolved (all beans injected) I do not think this construct works.

What you could do or try out is to remove the @PostConstruct and using normal setter injection. 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. And as expected references to other EJBs have not be resolved yet, so be aware of that.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top