简体   繁体   English

Java EE Bean注入另一个Bean

[英]Java EE Bean inject into another Bean

I'm making two beans say ABean and BBean. 我正在说两个豆,分别是ABean和BBean。 I want to inject BBean into ABean but this is causing null pointer errors, likely because the bean has yet to be instantiated. 我想将BBean注入ABean,但这会导致空指针错误,可能是因为该bean尚未实例化。 How can I inject beans in beans as such: 我如何像这样在bean中注入bean:

@Singleton
public class ABean {

  @Inject
  BBean bean;

  ....

}

I'm using java ee 7 with wildfly server. 我将Java ee 7与Wildfly服务器一起使用。 Both beans are singletons so BBean is also declared as: 两个bean都是单例,因此BBean也声明为:

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. 在没有依赖关系的情况下,我可以创建两个bean,因为其中确实包含必需的META-INF文件夹和beans.xml文件。 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. 也许您忘了添加beans.xml文件,以便在应用程序中启用CDI。 This is what the Java EE 6 Tutorial says http://docs.oracle.com/javaee/6/tutorial/doc/gjbnz.html : 这就是Java EE 6教程所说的http://docs.oracle.com/javaee/6/tutorial/doc/gjbnz.html

An application that uses CDI must have a file named beans.xml. 使用CDI的应用程序必须具有一个名为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. 对于Web应用程序,beans.xml文件必须位于WEB-INF目录中。 For EJB modules or JAR files, the beans.xml file must be in the META-INF directory. 对于EJB模块或JAR文件,beans.xml文件必须位于META-INF目录中。

did you remember to include a setter so the bean can be injected? 您还记得包括一个setter以便可以注入bean吗? @Inject does not work like @EJB. @Inject不能像@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) 同样,如前所述,在实例化拥有的bean之后,不要尝试使用该bean(不在构造函数中,仅在@ PostConstruct'ed方法中)

hope that helps. 希望能有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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