Alex Rivera | Logout

Can I use CDI constructor injection for EJBs?

Asked 2012-02-07T09:12:10.823
18

I want to do something like this:

@Stateless
public class GreeterEjb {


    private final Greeter greeter;


    @Inject
    public GreeterEjb(Greeter greeter) {
        this.greeter = greeter;
    }


    public String greet() {
        return greeter.greet();
    }
}

I tried it with Glassfish 3.1.1 and JBoss 7.0.2 with mixed results. Under some circumstances it works, under other circumstances it doesn't. See this thread in the Glassfisch forum if you are interested in the details.

The EJB 3.1 spec, section 4.9.2 Bean Classes says:

The class must have a public constructor that takes no parameters.

That sounds like constructor injection is not allowed for EJBs.

BUT the CDI spec says at the start of section 3 that Session Beans are supported by CDI. Section 3.2 then talks at length about CDI and EJBs but never mentions anything about constructor injection not working. Which makes me think that it should be allowed.

So, do the specs allow CDI constructor injection for EJBs or not?

Edit
Report

1 Answer

8

Constructor injection of EJBs is required in Java EE 6 ONLY IF CDI is enabled for the jar. If this not working in an appserver, file a bug.

Please also file an issue here - http://java.net/jira/browse/EJB_SPEC - to have the EJB language spec fixed (it's wrong).

This is tested in the CDITCK - https://github.com/jboss/cdi-tck/blob/master/impl/src/main/java/org/jboss/cdi/tck/tests/implementation/enterprise/definition/ExplicitConstructorSessionBean.java - but not for no-interface-views, so please raise an issue in https://issues.jboss.org/browse/CDITCK and we can add a test for your case.

answered 2012-02-07T17:06:14.580

Your Answer