简体   繁体   中英

Can CDI inject standard library POJOs into an EJB?

I can inject my own POJO into a managed object like this:

import javax.ejb.Stateless;
import javax.inject.Inject;
@Stateless
public class SomeEjb {
    @Inject
    private SomePojo somePojo;
}

And I have this POJO:

// No annotations
public class SomePojo {   
}

This works fine. If I inject the EJB into a JSF backing-bean, I can see that the value of somePojo is non-null value, as expected.

However, if I try to inject a java.util.Date into SomeEjb , I get the following exception on deployment:

Severe: Exception while loading the app : WELD-001408 Unsatisfied dependencies for type [Date] with qualifiers [@Default] at injection point [[field] @Inject private SomeEjb.date]
org.jboss.weld.exceptions.DeploymentException: WELD-001408 Unsatisfied dependencies for type [Date] with qualifiers [@Default] at injection point [[field] @Inject private SomeEjb.date]
    at org.jboss.weld.bootstrap.Validator.validateInjectionPoint(Validator.java:311)

SomeEjb now:

// No annotations
public class SomeEjb {
    @Inject
    private Date date;    
}

Date has a public, no-argument constructor, and I thought that's all CDI would need to "satisfy the dependency". I'm sure this behaviour is "to spec", but clearly there's a big hole in my understanding of CDI.

Can someone explain why this doesn't work? What's the difference between SomePojo and java.util.Date from a CDI perspective?

Context:

  • Java EE 6
  • GlassFish 3.1.2.2
  • I don't have a use-case for this. I know that I can just specify new Date() .

I can reproduce this with EAP 6.3 as well.

The problem most likely occurs because of using Java EE 6. The java.util.Date is located in rt.jar and this JAR does not contain a beans.xml file which would enable CDI. You can only inject objects from JARs containing a beans.xml.

A common workaround is to use a producer method to inject such an object. You have to wirte this producer yourself but you will be able to inject objects from arbitrary classes regardless to which JAR they belong.

As far as I know the behaviour changed in Java EE 7, where the beans.xml is optional in some cases: https://blogs.oracle.com/theaquarium/entry/default_cdi_enablement_in_java

Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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