What is exactly “container managed object” in Java 6 EE world?

故事扮演 提交于 2020-01-25 05:38:03

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!