【发布时间】:2018-12-17 13:02:30
【问题描述】:
我正在尝试将依赖项注入到 bean (Some/OtherImpl) 中,并使用 @Named 进行注释,但是当新的该 bean 的实例是在控制器 (MyCtrl) 中使用其生产者方法创建的。
但是,如果我尝试将 ConfigurationService 直接注入控制器,则方法 Resources#getConfiguratioService 会执行并创建 ConfigurationService 的新实例,该实例将被注入控制器。
看起来是这样的
public class Resources() {
@Produces
public ConfigurationService getConfigurationService() {
return new ConfigurationService(Constants.CONFIG);
}
}
public abstract class MyAbstractClass {
@Inject
private transient ConfigurationService configurationService; // getter+setter
}
@Named
public class SomeImpl extends MyAbstractClass implements Serializable {
// ...
}
@Named
public class OtherImpl extends MyAbstractClass implements Serializable {
// ...
}
@Named
@ViewScoped
public class MyCtrl {
@Inject
private SomeImpl someImpl;
@Produces
public SomeImpl getSomeImpl() {
return new SomeImpl(MyStringParam);
}
}
你能告诉我我在这里做错了什么吗?有没有办法解决它?每一个提示将不胜感激。提前谢谢!
【问题讨论】:
-
如果它是由
new创建的,它不受CDI控制,不会发生依赖注入。
标签: jakarta-ee cdi