从BeanManager将Cast Bean <! - ? - >转换为Servlet

时间:2016-09-17 16:34:50

标签: java servlets

我有一个EJB项目,并有以下注释:

@Retention(RUNTIME)
@Target(TYPE)
@Qualifier
public @interface AfterComplete {
}

我有2个用这个注释装饰的类。它们也是@Stateless

@AfterComplete
@Stateless
public class AfterCompletePrinter implements IAfterComplete {

  public void afterComplete(String someValue) {
    System.out.println("After complete printer: " + someValue);
  }

}


@AfterComplete
@Stateless
public class AfterCompleteErrPrinter implements IAfterComplete{

  public void afterComplete(String someValue) {
    System.err.println(someValue);
  }
}

在servlet中,我有:

@WebServlet("/")
public class DemoServlet extends HttpServlet {
  @Inject
  BeanManager beanManager;

  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    Set<Bean<?>> beans = beanManager
        .getBeans(Object.class,new AnnotationLiteral<AfterComplete>() {});

    for (Bean<?> bean : beans) {
      response.getWriter().print(bean.getBeanClass());
      // IAfterComplete iac = (IAfterComplete) bean;
    }
  }
}

我的servlet打印:

  
    

net.mikeski.ejb_annotations.AfterCompletePrinterclass     net.mikeski.ejb_annotations.AfterCompleteErrPrinter

  

但是,如果没有注释,该行会引发异常:

  
    

IAfterComplete iac =(IAfterComplete)bean;

  

例外是:

  
    

java.lang.ClassCastException:org.jboss.weld.bean.SessionBean无法强制转换为net.mikeski.ejb_annotations.IAfterComplete

  

如何使用bean执行某些操作以获取实现IAfterComplete的类的实例? bean.getName()返回null。

我在想是否可以获取其JNDI名称,我可以进行查找,但不知道该怎么做。

如果它有任何不同,这就是Wildfly 10。

1 个答案:

答案 0 :(得分:0)

所以,我发现答案有效,就像这样:

@Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    Set<Bean<?>> beans = beanManager
        .getBeans(Object.class, new AnnotationLiteral<AfterComplete>() {
        });

    for (Bean<?> bean : beans) {
      response.getWriter().print(bean.getBeanClass());
      IAfterComplete iac = (IAfterComplete) beanManager.getReference(bean, IAfterComplete.class, beanManager.createCreationalContext(bean));
      iac.afterComplete("After complete called on " + iac);
    }
  }

我把整个工作项目放在github上:https://github.com/mikebski/ejb-custom-annotations

这是一篇快速博客文章,其中有一些解释:

http://blog.mikeski.net/blog_post/487