2016-09-17 38 views
0

我有一個EJB項目,並具有以下注釋:演員豆<?>從BeanManager類的實例在Servlet的

@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)豆;

唯一的例外是:

java.lang.ClassCastException:org.jboss.weld.bean.SessionBean不能轉換到net.mikeski.ejb_annotations.IAfterComplete

我該如何處理bean以獲取實現IAfterComplete的類的實例? bean.getName()返回null。

我在想如果我能得到它的JNDI名稱,我可以做一個查詢,但不知道該怎麼做。

這是野驢10,如果它有任何區別。

+0

我找不到「@AfterComplete」的任何信息。它是否記錄在某處?它是哪個API? – markspace

+0

看看第一個代碼片段,它是註釋。 – mikeb

回答

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

相關問題