我正在尝试创建一个动态消息监听器并将其放入spring容器中。 我在我的spring xml文件中有一些Spring配置的监听器,它们完美无缺。 但我的代码听众不会:(
这就是我所做的。
DefaultListableBeanFactory factory = (DefaultListableBeanFactory) appContext.getAutowireCapableBeanFactory();
Object queue = null;
try {
queue = appContext.getBean(queueName);
} catch (BeansException e) {
}
if(queue==null) {
BeanDefinitionBuilder queueBuilder = BeanDefinitionBuilder.rootBeanDefinition(ActiveMQQueue.class);
queueBuilder.addConstructorArgValue(queueName);
factory.registerBeanDefinition(queueName,queueBuilder.getBeanDefinition());
}
// creating listener bean
String listenerName = "dynamicListener";
BeanDefinitionBuilder listenerBuilder = BeanDefinitionBuilder.rootBeanDefinition(listener);
factory.registerBeanDefinition(listenerName,listenerBuilder.getBeanDefinition());
// creating adapter bean
String beanName = "dynamicAdapterListener";
BeanDefinitionBuilder listenerAdapterBuilder = BeanDefinitionBuilder.rootBeanDefinition(MessageListenerAdapter.class);
listenerAdapterBuilder.addPropertyReference("delegate", listenerName);
listenerAdapterBuilder.addPropertyValue("defaultListenerMethod", null);
factory.registerBeanDefinition(beanName,listenerAdapterBuilder.getBeanDefinition());
//creating container bean
BeanDefinitionBuilder listenerContainerBuilder = BeanDefinitionBuilder
.rootBeanDefinition(DefaultMessageListenerContainer.class);
listenerContainerBuilder.addPropertyValue("destinationName", queueName);
listenerContainerBuilder.addPropertyReference("connectionFactory", "connectionFactory");
listenerContainerBuilder.addPropertyReference("messageListener", beanName);
listenerContainerBuilder.addPropertyValue("concurrency", String.valueOf(concurrency));
listenerContainerBuilder.addPropertyValue("cacheLevelName", "CACHE_AUTO");
listenerContainerBuilder.addPropertyValue("autoStartup", true);
listenerContainerBuilder.addPropertyValue("sessionAcknowledgeMode", 1);
String containerName = "listenerContainer";
factory.registerBeanDefinition(containerName, listenerContainerBuilder.getBeanDefinition());
DefaultMessageListenerContainer bean = (DefaultMessageListenerContainer) appContext.getBean(containerName);
// i even initialized bean to make sure it works but does'nt:(
bean.afterPropertiesSet(); // which initialized bean
创建所有bean并将其注入Spring ApplicationContext;但是监听器不会监听指定的队列。
任何想法如何在运行时创建Queue / Listener / Container / all?