【问题标题】:Not able to Autowire ExceptionListener无法自动装配 ExceptionListener
【发布时间】:2017-08-08 02:46:18
【问题描述】:

我创建了一个MessageListener,它将使用来自 Azure 服务总线的消息。在使用SingleConnectionFactory 创建连接时,我正在尝试设置ExceptionListener。我的ExceptionListener 和 Configuration 都在不同的类中。所以在我的配置类中,我试图自动装配一个实现ExceptionListener 的类。当我这样做时,我将 Autowired ExceptionListener 设为空。请让我知道我是否可以自动接线ExceptionListener。请在下面找到我的示例代码:

@Component
public class JMSExcepListener implements ExceptionListener{
@Autowired
private DefaultMessageListenerContainer listenerContainer;

@Autowired
private SingleConnectionFactory conFactory;

@Override
public void onException(JMSException exception) {
    listenerContainer.destroy();
    listenerContainer.initialize();
    try {
        conFactory.createConnection();
    } catch (JMSException e) {
        e.printStackTrace();
    }
    System.out.println("Exception");
}}

我正在SingleConnectionFactory注册这个监听器

@Configuration
public class AzureConfig{
@Autowired
    JMSExcepListener  jmsExcListener;
@Autowired
MessageConsumer messageConsumer;
    @Bean
    public SingleConnectionFactory jmsConnectionFactory() {
        SingleConnectionFactory cachingConnectionFactory = null;
        try {
            cachingConnectionFactory = new SingleConnectionFactory(ConnectionFactoryImpl.createFromURL(url));
            cachingConnectionFactory.setReconnectOnException(true);
            cachingConnectionFactory.setClientId(applicationName);
            singConnFactory.setExceptionListener(jmsExcListener);
        } catch (MalformedURLException e) {

        }
        return cachingConnectionFactory;
    }
    }
 @Bean
public DefaultMessageListenerContainer getContainer() {
    DefaultMessageListenerContainer container = new  DefaultMessageListenerContainer();
    container.setConnectionFactory(jmsConnectionFactory());
    container.setDestinationName(queueName);
    container.setMessageListener(messageConsumer);
    return container;
}
}

这里jmsExcListener 为空,但消息使用者工作正常请帮助。

是不是因为任何循环注入,因为我试图在 AzureConfig 中注入 ExcepitonListener 并试图将在 AzureConfig 中创建的 bean 注入到 ExceptionListener 中。如何解决?

【问题讨论】:

  • 确保您的 JmsExcListener 在组件扫描路径上并且组件扫描已启用
  • @borowis 组件扫描已启用,我能够自动装配位于同一包路径中的另一个组件
  • 那么这意味着您的 AzureConfig 不是由 spring 管理的,对吗?
  • @borowis AzureConfig 仅由 Spring 管理。更新了代码,我可以自动连接其他组件,但 ExceptionListener 单独作为 null
  • 好吧,这个 ExceptionListener 没有什么特别的,你当然应该可以自动装配它,但我无法从上面的 sn-p 中看出是什么原因。也许您可以提供更多代码?

标签: java spring spring-boot jms spring-jms


【解决方案1】:

如果您从未注意到这一点;你有一个循环依赖链。

JMSExcepListener 类需要 SingleConnectionFactory(通过 autowire) 在 AzureConfig 中创建 bean 又需要一个 JMSExcepListener(通过 autowire)。

解决方案总是这样:不要在配置类中的类级别自动装配依赖项。

【讨论】:

    猜你喜欢
    • 2012-01-27
    • 2016-10-09
    • 2020-05-04
    • 2014-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-21
    • 2015-07-17
    相关资源
    最近更新 更多