问题
I want to get bean from producer method in order to read its properties. In some scenarios the bean is a EJB Singleton
bean.
I've simplified my code to focus on the problem.
My simple qualifier:
@Qualifier
@Retention(RUNTIME)
@Target({TYPE, METHOD, FIELD, PARAMETER})
public @interface InjectMe {}
Simple producer:
@Dependent
public class SimpleProducer {
@Produces
@InjectMe
public String getInjectMe(InjectionPoint ip) {
// ip.getBean() returns null for some reason
return "ip=" + ip + ", bean=" + ip.getBean();
}
}
EJB (Singleton):
@Singleton
@Startup
public class SimpleSingleton {
@Inject
@InjectMe
private String injectMe;
@PostConstruct
public void init() {
System.out.println(injectMe);
}
}
Console output:
Info: ip=[BackedAnnotatedField] @Inject @InjectMe private com.test.ejb.SimpleSingleton.injectMe,
bean=null
When I change Singleton
bean to CDI
bean everything works fine (ip.getBean()
returns not null). It also worked in Java EE 6
even with Singleton
bean but it does not in Java EE 7
. I am using Glassfish 4 application server.
Is this behavior specified somewhere?
回答1:
Using
injectionPoint.getMember().getDeclaringClass()
works for me in WildFly 10.1.0 and I also quickly tested it in Payara Server 4.1.1.162 #badassfish (build 116). I also did a test on brand new Payara Server 4.1.1.164 #badassfish (build 28). However,I had to change the scope of the producer bean to @ApplicationScoped. Default scope did not work. In my case, it even makes sense :)
The
injectionPoint.getBean().getBeanClass()
method worked for me in the old Payara, but not in the new WildFly 10.1.0.Final and new Payara Server 4.1.1.164 #badassfish (build 28).
If you have a look at Payara, the current new version 164 contains Weld 2.4.0.Final and WildFly 10.1.0Final uses version 2.3.5.Final. In both versions, the classical code does not work !
The conclusion is, on older CDI implementations (Weld), it works. In some newer Weld (introduced in Payara 161), the behavior changed. I do not know if this is intentional or not.
However, the solution is to use
injectionPoint.getMember().getDeclaringClass()
and annotate the producer bean with
@javax.enterprise.context.ApplicationScoped
annotation.
来源:https://stackoverflow.com/questions/34643780/injectionpoint-getbean-returns-null-if-bean-is-an-ejb-bean-in-java-ee-7-cdi-1