我想做这样的事情:
@Stateless
public class GreeterEjb {
private final Greeter greeter;
@Inject
public GreeterEjb(Greeter greeter) {
this.greeter = greeter;
}
public String greet() {
return greeter.greet();
}
}
我用 Glassfish 3.1.1 和 JBoss 7.0.2 尝试过,结果好坏参半。在某些情况下它有效,在其他情况下则无效。
如果您是,请参阅 Glassfisch 论坛中的此帖子对细节感兴趣。
EJB 3.1 规范,第 4.9.2 Bean 类说:
该类必须有一个不带参数的公共构造函数。
听起来 EJB 不允许构造函数注入。
但是 CDI 规范 在第 3 节开头指出 CDI 支持会话 Bean。 3.2 节随后详细讨论了 CDI 和 EJB,但从未提及有关构造函数注入不起作用的任何内容。这让我认为应该允许这样做。
那么,规范是否允许 EJB 的 CDI 构造函数注入?
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?
发布评论
评论(2)
Kris 和 Pete Muir 终于说服了我:EJB 必须即使使用另一个构造函数进行注入,也有一个公共的无参数构造函数。同时使用两个构造函数很奇怪,但它确实有效。谢谢你们。
已在 Glassfish 3.1.1、JBoss 7.0.2 和 TomEE 1.0.0-beta-2 上成功测试。
Kris and Pete Muir have finally convinced me: The EJB must have a public no-arg constructor even if another constructor is used for injection. Weird to use two constructors at the same time, but it works. Thanks guys.
Successfully tested on Glassfish 3.1.1, JBoss 7.0.2 and TomEE 1.0.0-beta-2.
仅当为 jar 启用了 CDI 时,Java EE 6 中才需要 EJB 的构造函数注入。如果这在应用程序服务器中不起作用,请提交错误。
另请在此处提出问题 - http://java.net/jira/browse/EJB_SPEC -修复 EJB 语言规范(这是错误的)。
这是在 CDITCK 中测试的 - https://github.com/jboss/cdi-tck/blob/master/impl/src/main/java/org/jboss/cdi/tck/tests/implementation/enterprise/definition/ExplicitConstructorSessionBean。 java - 但不适用于无界面视图,因此请在 https://issues.jboss.org/browse/CDITCK 我们可以为您的案例添加测试。
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.