问题
I tried to use CDI for my struts action running on glassfish. But java dependency injection does not work for it. It works for JSF but not struts. As I read -- container injects dependencies to any instance of container managed bean (bean created by container).
So, what is "container managed bean"? Any POJO? Or only jsf back bean, ejb-bean and so on?
And how it happens? Glassfish has special class-loader to inject?
回答1:
I only can inject your CDI beans in managed classes. Struts creates its own instances, so Struts beans are no container managed.
I don't know if Struts has a plugin able to inject CDI beans, but you can lookup the Bean Manager in JNDI tree.
public BeanManager getBeanManager() {
try {
Context jndiContext = new InitialContext();
return (BeanManager) jndiContext.lookup("java:comp/BeanManager");
} catch (NamingException e) {
// handle the exception
}
}
In your application you can use this:
BeanManager manager = BeanManagerUtil.getBeanManager();
manager.getBeans(MyClass.class);
For each bean returned by getBeans method you need to get the bean reference
CreationalContext ctx = manager.createCreationalContext(bean);
MyClass myClass = manager.getReference(bean, MyClass.class, ctx);
Regards
来源:https://stackoverflow.com/questions/4932121/what-is-exactly-container-managed-object-in-java-6-ee-world