代码之家  ›  专栏  ›  技术社区  ›  pike

确保Spring应用程序的其余部分即使在一个bean在运行时出错时也能运行

  •  0
  • pike  · 技术社区  · 7 年前

    现在,我正在开发一个包含多个组件的Spring应用程序,其中包括一个RabbitMQ组件。

    RabbitMQ连接的初始化是通过在应用程序启动时自动激活的配置bean实现的。

    下面是我的RabbitMQ配置文件:

    @Configuration
    @PropertySources({
            @PropertySource("classpath:message.properties"),
            @PropertySource("classpath:rabbitmq.properties")
    })
    @EnableRabbit
    public class MessageConfiguration {
    
        private static final String MESSAGE_HOST_PROPERTY = "message.host";
    
        private static final String FACTORY_USERNAME_PROPERTY = "rabbitmq.username";
        private static final String FACTORY_PASSWORD_PROPERTY = "rabbitmq.password";
    
    
        private Environment environment;
    
    
    
        @Autowired
        public MessageConfiguration(Environment environment) {
            this.environment = environment;
        }
    
    
        @Bean
        public AmqpTemplate publishTemplate() {
            RabbitTemplate result = new RabbitTemplate(connectionFactory());
            return result;
        }
    
    
        @Bean
        public ConnectionFactory connectionFactory() {
            CachingConnectionFactory connectionFactory = new CachingConnectionFactory(environment.getProperty(MESSAGE_HOST_PROPERTY));
            connectionFactory.setUsername(environment.getProperty(FACTORY_USERNAME_PROPERTY));
            connectionFactory.setPassword(environment.getProperty(FACTORY_PASSWORD_PROPERTY));
            return connectionFactory;
        }
    }
    

    在Bean connectionFactory中,如果我提供了错误的用户名和密码,我的应用程序将遇到身份验证错误:

    Caused by: org.springframework.context.ApplicationContextException: Failed to start bean 'org.springframework.amqp.rabbit.config.internalRabbitListenerEndpointRegistry'; nested exception is org.springframework.amqp.AmqpIllegalStateException: Fatal exception on listener startup
        Caused by: org.springframework.amqp.AmqpIllegalStateException: Fatal exception on listener startup
        Caused by: org.springframework.amqp.rabbit.listener.exception.FatalListenerStartupException: Authentication failure
        Caused by: org.springframework.amqp.AmqpAuthenticationException: com.rabbitmq.client.AuthenticationFailureException: ACCESS_REFUSED - Login was refused using authentication mechanism PLAIN. For details see the broker logfile.
    

    有没有一种方法可以只包含RabbitMQ bean错误,而不包含所有其他组件,这样应用程序的其余部分就可以运行?

    1 回复  |  直到 7 年前
        1
  •  1
  •   Gary Russell    7 年前

    身份验证错误被认为是致命的。

    FatalListenerStartupException

    您不显示侦听器配置,但可以通过 autoStartup 所有物如果为false,则上下文将始终加载为ok。

    start() 代码中的容器并捕获异常。