简体   繁体   中英

Java EE Bean inject into another Bean

I'm making two beans say ABean and BBean. I want to inject BBean into ABean but this is causing null pointer errors, likely because the bean has yet to be instantiated. How can I inject beans in beans as such:

@Singleton
public class ABean {

  @Inject
  BBean bean;

  ....

}

I'm using java ee 7 with wildfly server. Both beans are singletons so BBean is also declared as:

public class BBean {

  @PostConstruct
  public void startup() {
    ..
  }

  ..
}

With out the dependency, I'm able to create both beans as I do have the necessary META-INF folder and beans.xml file with in it. I'm however coming to the conclusion that this might be bad practice/ anti-pattern. Anyway I'm not using this approach anymore.

Perhaps you forgot to add the beans.xml file, in order to enable CDI in your application. This is what the Java EE 6 Tutorial says http://docs.oracle.com/javaee/6/tutorial/doc/gjbnz.html :

An application that uses CDI must have a file named beans.xml. The file can be completely empty (it has content only in certain limited situations), but it must be present. For a web application, the beans.xml file must be in the WEB-INF directory. For EJB modules or JAR files, the beans.xml file must be in the META-INF directory.

did you remember to include a setter so the bean can be injected? @Inject does not work like @EJB.

also, like previously indicated, do not try to use the bean until after the owning bean is instantiated (not in constructor, only in @PostConstruct'ed method)

hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM