Quarkus框架:使用bean.xml文件定义CDI Bean
Quarkus框架:使用bean.xml文件定义CDI Bean
在Quarkus框架中,您可以通过创建名为'beans.xml'的文件来定义CDI bean。在这个文件中,可以定义bean的作用域、注入点、类型等。
以下是如何在Quarkus中使用bean.xml文件的步骤:
-
在项目的'src/main/resources/META-INF'目录下创建一个名为'beans.xml'的文件。
-
在'beans.xml'文件中定义CDI bean。例如,以下代码定义了一个名为'MyBean'的bean:
<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'>
<alternatives>
<class>com.example.MyBean</class>
</alternatives>
</beans>
在这个例子中,'bean-discovery-mode'属性被设置为'annotated',这告诉Quarkus只扫描在代码中使用'@javax.inject.Named'或'@javax.enterprise.context.NormalScope'注解的类。
- 在代码中使用bean。例如,在以下代码中,'MyBean'被注入到'MyService'中:
@ApplicationScoped
public class MyService {
@Inject
MyBean myBean;
// ...
}
这样,就可以通过'MyService'访问'MyBean'了。
希望这篇文章对你有所帮助!
原文地址: https://www.cveoy.top/t/topic/llju 著作权归作者所有。请勿转载和采集!