Home > Back-end >  How to create bean based on property in springboot
How to create bean based on property in springboot

Time:11-18

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')}")

CodePudding user response:

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

CodePudding user response:

similar to conditional on expression, spring has conditional on property that can do this https://www.baeldung.com/spring-conditionalonproperty

I've used this to create a bean of a class that implements an interface when 2 classes implement the interface. Only 1 of the conditionals on both of the beans should evaluate to true so that you don't get a conflict error.

  • Related