How to create bean based on property in springboot

Issue

I have two beans in my application configuration. I would like to enable only one bean based on property, Can we make bean conditional based on property ?

Ex: Let say if I have this property enable.userconnection: true, I would like to create UserCredentialsConnectionFactoryAdapter bean. If I set that value to false. I would like to enable CachingConnectionFactory bean.

@Bean
public CachingConnectionFactory connectionFactory(
  CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
  connectionFactory.setTargetConnectionFactory(axonConnectionFactory);
  connectionFactory.setReconnectOnException(true);
  connectionFactory.setSessionCacheSize(jmsSessionCacheSize);
  return connectionFactory;
}

@Bean
public UserCredentialsConnectionFactoryAdapter userCredentialsConnectionFactoryAdapter()
    throws Exception {
  UserCredentialsConnectionFactoryAdapter connectionFactoryAdapter =
      new UserCredentialsConnectionFactoryAdapter();
    connectionFactoryAdapter.setUsername(getUsername());
    connectionFactoryAdapter.setPassword(getPassword());
    connectionFactoryAdapter.setTargetConnectionFactory(
        messagingJMSService().getConnectionFactory(getName()));
  return connectionFactoryAdapter;
}

I tried this way, which works fine based on the profile. But, I would like to apply similar logic making use of property.

@ConditionalOnExpression("#{!environment.getProperty('spring.profiles.active').contains('a') && !environment.getProperty('spring.profiles.active').contains('b')}")

Solution

You can try something like this

@Bean
@ConditionalOnProperty(prefix = "my.property.prefix", name = "myProperty")
public MyBean myBean(){
  return new MyBean();
}

Refer – Spring boot ConditionalOnProperty docs

Answered By – ajesh

Answer Checked By – Mary Flores (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.