我的应用程序部署在JOnAS 5.2.2
不CDI
支持EJB
. 我需要使用CDI
它EJB
。我知道如何CDI
在应用程序的 WAR 部分上使用,但我部分不知道EJB
。
有没有办法在不支持的容器中添加CDI
对应用程序的支持?EJB
我的老板不会为支持它的版本升级服务器。
[编辑] 我使用 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 注释,但我不明白怎么做。