为什么@Inject 在作为 jar 文件导入到另一个项目后不起作用?
Why @Inject not work after import as a jar file to another project?
我有一个 Maven 基础 Java EE 项目:core-project
。
在这个项目中,我使用 @Inject
并且一切都按预期工作。
但是在将此项目作为依赖项导入到另一个项目 parent-project
后,注入的字段为空。
为什么将一个jar文件导入其他项目后,注入不起作用?
如果您的字段为空,这意味着无法解析匹配的 bean。
如果它们在另一个包中,您需要一个文件 beans.xml
(可以为空)。
Configuring a CDI Application
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.
因此请确保您的 core-project
和 parent-project
中有一个 beans.xml
。对于 Maven:
来自:
For EJB and JAR packaging you should place the beans.xml in
src/main/resources/META-INF/. For WAR packaging you should place the
beans.xml in src/main/webapp/WEB-INF/
另一个原因可能是您的 Bean 被注释为 @Alternative
或 @Specializes
。在这种情况下,您需要在 beans.xml:
中指定 bean 作为替代
<beans ... >
<alternatives>
<class>sample.package.YourAlternativeBean</class>
</alternatives>
</beans>
有关详细信息,请参阅 http://docs.oracle.com/javaee/6/tutorial/doc/gjsdf.html。
我有一个 Maven 基础 Java EE 项目:core-project
。
在这个项目中,我使用 @Inject
并且一切都按预期工作。
但是在将此项目作为依赖项导入到另一个项目 parent-project
后,注入的字段为空。
为什么将一个jar文件导入其他项目后,注入不起作用?
如果您的字段为空,这意味着无法解析匹配的 bean。
如果它们在另一个包中,您需要一个文件 beans.xml
(可以为空)。
Configuring a CDI Application
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.
因此请确保您的 core-project
和 parent-project
中有一个 beans.xml
。对于 Maven:
来自:
For EJB and JAR packaging you should place the beans.xml in src/main/resources/META-INF/. For WAR packaging you should place the beans.xml in src/main/webapp/WEB-INF/
另一个原因可能是您的 Bean 被注释为 @Alternative
或 @Specializes
。在这种情况下,您需要在 beans.xml:
<beans ... >
<alternatives>
<class>sample.package.YourAlternativeBean</class>
</alternatives>
</beans>
有关详细信息,请参阅 http://docs.oracle.com/javaee/6/tutorial/doc/gjsdf.html。