Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This is my final approach:</p> <p>I spend a PostConstruct method to my MessageDispachter where I look for all message handler beans. For each of these beans I get their annotation value and a reference to the bean (which also includes creation of the bean). Then I store both, the annotation value and the bean reference into my messageHandlerMap. There is a lot of CDI delegating and interception involved, but it works:</p> <pre><code>public class MessageDispatcher { private Map&lt;String, MessageHandler&gt; messageHandlerMap = new HashMap&lt;String, MessageHandler&gt;(); @Inject DefaultMessageHandler defaultMessageHandler; @Inject BeanManager beanManager; @PostConstruct public void registerHandlers() { Set&lt;Bean&lt;?&gt;&gt; messageHandlerBeans = beanManager.getBeans(MessageHandler.class, new MessageTypeLiteral()); for (Bean&lt;?&gt; bean : messageHandlerBeans) { String key = bean.getBeanClass().getAnnotation(MessageType.class).value(); if (!key.isEmpty()) { CreationalContext&lt;?&gt; creationalContext = beanManager.createCreationalContext(bean); MessageHandler messageHandler = (MessageHandler) beanManager.getReference(bean, MessageHandler.class, creationalContext); messageHandlerMap.put(key, messageHandler); } } } public MessageHandler getMessageHandler(String key) { MessageHandler messageHandler = (MessageHandler) messageHandlerMap.get(key); return messageHandler != null ? messageHandler : defaultMessageHandler; } } @Documented @Qualifier @Retention(RUNTIME) @Target({TYPE, METHOD, FIELD, PARAMETER}) public @interface MessageType { @Nonbinding String value(); } @SuppressWarnings("all") public class MessageTypeLiteral extends AnnotationLiteral&lt;MessageType&gt; implements MessageType { private static final long serialVersionUID = 1L; @Override public String value() { return ""; } } public class DefaultMessageHandler implements MessageHandler { @Inject ResourceBundleProvider resourceBundleProvider; @Override public void processMessage(String inputMesssage) { ... @MessageType("first") public class FirstMessageHandler implements MessageHandler { @Inject ResourceBundleProvider resourceBundleProvider; @Override public void processMessage(String inputMesssage) { ... </code></pre> <p>The <code>@NonBinding</code> annotation in the <code>@MessageType</code> annotation seems to be important to find all beans annotated with <code>@MessageType("xxx")</code> independent of the actual annotation value (here: xxx).</p> <p>I hope this explains the important things. For further details please ask me</p> <p>Sebastian</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload