Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Instantiate @configuration bean based on property value from properties file

I have two classes/beans annotated with @Configuration and I have to instantiate based on the value from the property file.

RemoteServer1.java

@Configuration
public class RemoteServer1 {
    //some authentication logic goes here
}

RemoteServer2.java

@Configuration
public class RemoteServer2 {
    //some authentication logic goes here
}

application.properties

remote.server.location=RemoteServer1

Now i want to instantiate @Configuration class/bean matched with value from property file.

like image 996
laxmi Avatar asked Sep 12 '25 10:09

laxmi


1 Answers

I would suggest you look into the @Contidional... annotations in Spring Boot to conditionally activate Beans, Configurations etc.

http://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/autoconfigure/condition/ConditionalOnProperty.html

This should work looking at the property and config. For the first configuration,

@ConditionalOnProperty(name="remote.server.location", havingValue="RemoteServer1",  matchIfMissing=false)

Second,

@ConditionalOnProperty(name="remote.server.location", havingValue="RemoteServer2",  matchIfMissing=false)

Looks for the property name, matches on havingValue, will not evaluate to true if the property is missing.

like image 105
Darren Forsythe Avatar answered Sep 14 '25 01:09

Darren Forsythe