以下是我用來將CDI上下文bean注入非上下文對象的代碼。將CDI上下文bean注入到現有非上下文bean中的正確方法?
// My controller is Non-contextual bean
public class MyController extends Controller {
@Inject
ModelBinder modelBinder;
@Inject
ApplicationConfig applicationConfig;
private CreationalContext<Controller> creationalContext;
public void setCreationalContext(CreationalContext<Controller> creationalContext) {
this.creationalContext = creationalContext;
}
public CreationalContext<Controller> getCreationalContext() {
return creationalContext;
}
// Other fields
}
代碼來初始化myController的
// Create Non-contextual bean
MyController controller = new MyController();
AnnotatedType<?> at = beanManager.createAnnotatedType(controller.getClass());
InjectionTarget<Controller> it = (InjectionTarget<Controller>)beanManager.createInjectionTarget(at);
CreationalContext<Controller> creationalContext = beanManager.createCreationalContext(null);
// Perform inject
it.inject(controller, creationalContext);
// Store creationalContext related
controller.setCreationalContext(creationalContext);
代碼來破壞myController的
// controller is instance of MyController
AnnotatedType<?> at = beanManager.createAnnotatedType(controller.getClass());
InjectionTarget<Controller> it = (InjectionTarget<Controller>)beanManager.createInjectionTarget(at);
it.dispose(controller);
controller.getCreationalContext().release();
今天,我的團隊領導找我談過,他說:因爲ModelBinder的,ApplicationConfig是CDI應用程序範圍bean,所以我不需要記錄ITE代碼破壞控制器和編碼他建議象下面這樣:
// New MyController
public class MyController extends Controller {
@Inject
ModelBinder modelBinder;
@Inject
ApplicationConfig applicationConfig;
// Do not need to store creationalContext
//private CreationalContext<Controller> creationalContext;
//public void setCreationalContext(CreationalContext<Controller> creationalContext) {
// this.creationalContext = creationalContext;
//}
//public CreationalContext<Controller> getCreationalContext() {
// return creationalContext;
//}
// Other fields
}
新代碼來初始化myController的
// Create Non-contextual bean
MyController controller = new MyController();
AnnotatedType<?> at = beanManager.createAnnotatedType(controller.getClass());
InjectionTarget<Controller> it = (InjectionTarget<Controller>)beanManager.createInjectionTarget(at);
CreationalContext<Controller> creationalContext = beanManager.createCreationalContext(null);
// Perform inject
it.inject(controller, creationalContext);
// Do not need to store creationalContext related
// controller.setCreationalContext(creationalContext);
新代碼來破壞myController的
// No need code to destroy the controller
任何人有什麼想法?非常感謝!
我不得不問,爲什麼你甚至自己實例化控制器?爲什麼不使用CDI容器來獲取對它的引用? – 2014-11-05 17:29:14