[英]what is the purpose of including empty beans.xml in CDI implemenations projects?
我在我的 JSF-EJB-JPA Web 应用程序中使用weld
,CDI 的一个 RI 作为依赖项注入组件。 我在我的项目中看到ejb.jar
中的META-INF/beans.xml
和 WAR 中的WEB-INF/beans.xml
中有空的 beans.xml。 我不明白为什么我们需要在该文件中没有定义任何内容时保留空的beans.xml
?
CDI 需要在启动时扫描 bean 存档的所有类并触发一系列事件,因为几乎所有类都会自动成为托管 bean( 在此处阅读更多内容),即使它没有任何注释。
这会产生相当多的开销,尤其是对于不打算包含任何 bean 的 jar 文件,因此通过包含beans.xml
来明确指示应扫描哪些 bean 档案是有益的。
一个完全空的beans.xml
与在存档中有一个beans.xml
具有以下内容相同:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
bean-discovery-mode="all">
</beans>
由于bean-discovery-mode="all"将扫描存档以查找 bean。 无需注释它们。
一个不存在的beans.xml
它与在存档中具有以下内容的beans.xml
相同:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
bean-discovery-mode="annotated">
</beans>
由于bean-discovery-mode="annotated"存档将在被注释的类中扫描 bean(例如@Dependent
)。 所有其他类将被忽略,因此不能作为 bean 注入。
第三个选项是声明bean-discovery-mode="none"在这种情况下服务器从不扫描 bean 的存档。
现在对于您想将类作为 bean 加载但无法访问存档(例如外部库)并且类没有注释的情况,解决方案是使用Producer 方法(带或不带限定符)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.