【发布时间】:2014-03-10 07:09:41
【问题描述】:
我的应用程序部署在不支持CDI 的JOnAS 5.2.2 上EJB。我需要在那个EJB 上使用CDI。我知道如何在应用程序的 WAR 部分使用 CDI,但我不知道在 EJB 部分。
有没有办法在不支持的容器中为EJB 应用程序添加对CDI 的支持?
我的老板不会为支持它的版本升级服务器。
[编辑] 我使用 CDI-WELD:我找到了解决方案的开始:
//CDI uses an AnnotatedType object to read the annotations of a class
AnnotatedType<DAOTest> type = beanManager.createAnnotatedType(DAOTest.class);
//The extension uses an InjectionTarget to delegate instantiation, dependency injection
//and lifecycle callbacks to the CDI container
InjectionTarget<DAOTest> it = beanManager.createInjectionTarget(type);
//each instance needs its own CDI CreationalContext
CreationalContext ctx = beanManager.createCreationalContext(null);
//instantiate the framework component and inject its dependencies
test = it.produce(ctx); //call the constructor
System.out.println("instance" + test);
it.inject(test, ctx); //call initializer methods and perform field injection
it.postConstruct(test); //call the @PostConstruct method
test.test();
it.preDestroy(test); //call the @PreDestroy method
it.dispose(test); //it is now safe to discard the instance
ctx.release(); //clean up dependent objects
我已经像这样在 DAOTest 中注入另一个测试:
@Named
@Dependent
public class DAOTest implements Serializable {
private static final long serialVersionUID = 1L;
@Persitence(value = "CDI-ejb")
private EntityManager em;
@Inject
private User user;
public void test(){
System.out.println(user.getName());
em.getClass();
}
public EntityManager getEm() {
return em;
}
public void setEm(EntityManager em) {
this.em = em;
}
public DAOTest() {
// TODO Auto-generated constructor stub
}
}
它有效,但 EntityManager 无法通过 @PersistenceContext 解析。我想我必须使用 @Produce 注释,但我不明白怎么做。
【问题讨论】:
标签: jakarta-ee ejb cdi jonas