我的Web应用程序仅适用于META-INF,而不适用于包括bean.xml的WEB-INF.为什么? [英] My web app works only with META-INF instead of WEB-INF including beans.xml. Why?

查看:85
本文介绍了我的Web应用程序仅适用于META-INF,而不适用于包括bean.xml的WEB-INF.为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究Java中的依赖注入示例,并且大多数文档都强调我必须在

I am working on examples of Dependency Injection in java, and most of the documents highlights that I have to put an empty beans.xml in

  • META-INF(如果它是jar应用程序)
  • 如果是Web应用程序,则为WEB-INF

因此,我使用战争类型包装,但是,仅当我将beans.xml放在META-INF文件夹中时,我的应用程序才能工作.我对为什么它会以这种方式有些困惑?我将战争文件部署在JBOSS/WildFly容器中.

So, I use war type packaging but, my application only works if I put beans.xml in META-INF folder. I am confused a little bit about why it is working with that way ? I deploy my war file in JBOSS/WildFly container.

这是我简单的 pom.xml

beans.xml位于src/main/resources/META-INF

beans.xml lies in src/main/resources/META-INF

还可以在这里看到我仅用于注入bean的注释.

Also here you can see which annotations I only used for injecting the beans.

AutoService.java

AutoService.java

public interface AutoService {
    void getService();
}

BMWAutoService.java

BMWAutoService.java

@Named("bmwAutoService")
public class BMWAutoService implements AutoService{

    @Override
    public void getService() {
        System.out.println("You chose BMW auto service");
    }
}

AutoServiceCaller.java

AutoServiceCaller.java

@Named
public class AutoServiceCallerImp implements AutoServiceCaller{

    private AutoService bmwAutoService;

    @Inject
    public AutoServiceCallerImp(@Named("bmwAutoService") AutoService bmwAutoService) {

        this.bmwAutoService = bmwAutoService;
    }

    @Override
    public void callAutoService() {
        // get bmw's auto service
        bmwAutoService.getService();
    }
}

推荐答案

这取决于您在何处使用注释.如果您的Web模块中有EJB bean,并且正在这些bean中使用注入,那么与纯ejb模块一样,您将需要在META-INF中具有beans.xml.如果要在Web组件(Servlet,过滤器,JSF Bean)中使用CDI注入,则必须在WEB-INF中使用它.您也可能在两个地方都需要它们(如果在两种组件中都使用过).

It depends where you are using annotations. If you have EJB beans in your web module and are using injections in these beans, then you will need to have beans.xml in the META-INF as it would be in case of pure ejb module. If you are using CDI injections in web components (servlets, filters, JSF beans) then you would have to have it in WEB-INF. You may also need them in both places (if used from both kind of components).

这篇关于我的Web应用程序仅适用于META-INF,而不适用于包括bean.xml的WEB-INF.为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆