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

Ensure rest of Spring application runs even when one bean has errors during runtime

现在我正在开发一个 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 无关的我的应用程序的其余部分不会 运行。

有没有一种方法可以将 RabbitMQ bean 错误包含在自身而不是所有其他组件中,以便应用程序的其余部分可以 运行?

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

对于暂时性错误(例如代理未 运行),应用程序将启动并尝试重新连接。

FatalListenerStartupException

您没有显示您的侦听器配置,但您可以通过 autoStartup 属性 将侦听器容器配置为不自动启动。如果为 false,上下文将始终加载正常。

然后您可以尝试 start() 代码中的容器并捕获异常。