简体   繁体   English

替代CDI注入不能按预期工作

[英]Alternative CDI injection not working as expected

I have two classes that implement an interface. 我有两个实现接口的类。 The one is annotated as @Default and @Named . 一个注释为@Default@Named The other is annotated as @Alternative 另一个注释为@Alternative

@Default
@Named
public class ListService implements IListService {
    @Override
    public void doSomething()
       print("default");
    }
}

@Alternative
public class ListServiceMock extends BaseServiceMock implements IListService {
    @Override
    public void doSomething()
       print("mock");
    }

}

The injection happens like this: 注射发生如下:

public class SomeNavigator extends AbstractNavigator {

    private IListService listService;

    @Inject
    public SomeNavigator(IListService listService) {
        this.listService = listService;
    }

    public void doNavigate() {
       this.listService.doSomething(); // Always prints "mock"
    }
}

My beans.xml file is in /src/main/webapp/WEB-INF/beans.xml and the project is built and packaged by Maven as a war file and deployed to JBoss EAP 6.3.3.GA (in a Docker container) 我的beans.xml文件位于/src/main/webapp/WEB-INF/beans.xml中,该项目由Maven构建和打包为war文件,并部署到JBoss EAP 6.3.3.GA (在Docker容器中)

I believe that the alternative bean ListServiceMock will only be injected if I include it in the beans.xml file like this: 我相信只有将bean包含在beans.xml文件中才会注入替代bean ListServiceMock如下所示:

<?xml version="1.0"?>
<beans bean-discovery-mode="all" version="1.1"
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:weld="http://jboss.org/schema/weld/beans"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                     http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd">

    <alternatives>
        <class>service.alternative.ListServiceMock</class>
    </alternatives>
</beans>

However regardless of if that section is in the beans.xml or not the alternative bean is always used. 但是,无论该部分是否在beans.xml ,都始终使用备用bean。

Is there a reason why it seems the beans.xml file is ignored in this case and the alternative bean is always selected for injection? 在这种情况下是否有理由忽略beans.xml文件并且始终选择替代bean进行注入?

Appears to be related to the XML namespaces in the beans.xml file. 似乎与beans.xml文件中的XML命名空间相关。 I swthced to these namespaces and it's working now. 我开始使用这些命名空间,现在它正在运行。

<beans xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
      http://java.sun.com/xml/ns/javaee 
      http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">

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

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