GlassFish 3.1 的托管 bean 的 CDI 实现是否支持构造函数注入(inject)?我有一个 @Singleton
我想使用构造函数注入(inject)向其中注入(inject)另一个托管 bean(包含在同一个 EJB 模块中)的 EJB。现场注入(inject)确实有效。但是通过构造函数注入(inject),我得到了 NullPointerException
来自 AbstractSingletonContainer
.
这确实有效:
@Singleton
public class FooBean implements Foo {
@Inject private BarBean bar;
}
这不起作用:
@Singleton
public class FooBean implements Foo {
private final BarBean bar;
@Inject
public FooBean(BarBean bar) {
this.bar = bar;
}
}
最佳答案
CDI 确实支持直接字段注入(inject)、初始化方法参数注入(inject)和构造函数参数注入(inject)。从 CDI 1.0 规范:
3.7. Bean constructors
When the container instantiates a bean class, it calls the bean constructor. The bean constructor is a constructor of the bean class.
The application may call bean constructors directly. However, if the application directly instantiates the bean, no parameters are passed to the constructor by the container; the returned object is not bound to any context; no dependencies are injected by the container; and the lifecycle of the new instance is not managed by the container.
3.7.1. Declaring a bean constructor
The bean constructor may be identified by annotating the constructor
@Inject
.@SessionScoped public class ShoppingCart implements Serializable { private User customer; @Inject public ShoppingCart(User customer) { this.customer = customer; } public ShoppingCart(ShoppingCart original) { this.customer = original.customer; } ShoppingCart() {} ... } @ConversationScoped public class Order { private Product product; private User customer; @Inject public Order(@Selected Product product, User customer) { this.product = product; this.customer = customer; } public Order(Order original) { this.product = original.product; this.customer = original.customer; } Order() {} ... }
If a bean class does not explicitly declare a constructor using
@Inject
, the constructor that accepts no parameters is the bean constructor.If a bean class has more than one constructor annotated
@Inject
, the container automatically detects the problem and treats it as a definition error.If a bean constructor has a parameter annotated
@Disposes
, or@Observes
, the container automatically detects the problem and treats it as a definition error.A bean constructor may have any number of parameters. All parameters of a bean constructor are injection points.
我想知道您的问题是否与 WELD-141 有关尽管。
引用
关于dependency-injection - GlassFish、CDI 和构造函数注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3541448/