Search code examples
javaspring-bootjms

How to make Spring Boot start up successfully even with some bean creation fails?


I have a JMS bean in Spring Boot be like:

@Configuration
public class JmsConfig {
    @Value("${broker.uri}")
    private String brokerUri;

    @Bean
    public ActiveMQConnectionFactory connectionFactory(){
        ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory();
        connectionFactory.setBrokerURL(brokerUri);
        return connectionFactory;
    }

    @Bean
    public JmsTemplate jmsTemplate(){
        JmsTemplate template = new JmsTemplate();
        template.setConnectionFactory(connectionFactory());
        return template;
    }

    @Bean
    public DefaultJmsListenerContainerFactory jmsListenerContainerFactory() {
        DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory());
        factory.setConcurrency("1-1");
        return factory;
    }
}

This broker url seems only working in production. There is no corresponding url in dev, and our system does not allow dev and production running with different packages which means my local pc must run with same code. And this non-working broker url somehow leads this jmsTemplate initialization failure, which leads the Spring Boot context to fail to start up.

Can we make this bean's failure not cause Spring Boot start failure? I tried use try catch and return null for the 3 beans.. didn't work.


Solution

  • I would try something like:

    @Configuration
    @ConditionalOnExpression(value = "'${jms.enabled:false}' == 'true'")
    public class JmsConfig {
    ...