Search code examples
javadependency-injectionejb

Factory returns Bean with EJB injected field Null


I've got a Factory class in Java with some methods which return some Java Bean. All of these Java Beans have some DAO object as fields which are injected with the annotation @EJB. However in every case these DAO are all Null, so I suppose I've a problem with EJB injection. I use WebLogic for deploy. Any suggestions to resolve the issue?

//Factory class
public class Factory extends AbstractFactory {

    @Override
    public InterfaceService getService() {
        return new ClassBean();
    }
}

//Bean class
@Stateless(mappedName = "ClassBean")
@LocalBean
public class ClassBean implements IBeanService {

    @EJB(beanName = "ClassDAO")
    private ClassDAO classDAO;


    public List<String> getList() throws ExpectedModelException {
        return classDAO.getStringList(); //this one throws NullPointerException
}

Solution

  • Never create Enterprise-Beans using new. The creation, caching, deletion,... is done by the container.

    You must declare ClassDao as @Stateless or @Singleton, ... and the container will create and find it, hopefully if the names are correct. The Factory is not necessary.