Is @Dependent scope not default in Wildfly?

2019-02-21 03:51发布

I have some troubles with injecting POJOs via @Inject using Wildfly. The documentation clearly states:

@Dependent - The default scope if none is specified; it means that an object exists to serve exactly one client (bean) and has the same lifecycle as that client (bean).

However, when I have two classes:

@Singleton
@Startup
public class A{
    @Inject
    private B b;
}

public class B{
    public B(){}
}

I keep getting:

Unsatisfied dependencies for type B with qualifiers @Default at injection point [BackedAnnotatedField] @Inject [...]

When I add @Dependent everything works like a charm. Am I missing something? Is this behavior wildfly-specific? Hope you can help, thanks.

1条回答
贼婆χ
2楼-- · 2019-02-21 04:12

When using CDI in Java EE 7 (CDI 1.1), the default bean discovery mode is annotated. Which means that any bean with an explicitly specified scope is available for injection.

So to make your bean B available for injection, you can either:

  1. Declare an explicit scope on class B (that's what you are doing when putting @Dependent)
  2. Declare a beans.xml file with the bean-discovery-mode attribute set to all. This will make all beans of your archive available for injection (same behavior than Java EE 6 (CDI 1.0)).

The beans.xml file must be in the META-INF folder and looks like:

<?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"
       version="1.1" 
       bean-discovery-mode="all">

</beans>

However, i would not recommend using bean-discovery-mode="all".

查看更多
登录 后发表回答