Spring Boot: Multiple similar ConfigurationProperties with different Prefixes
I achieved almost same thing that you trying. first, register each properties beans.
@Bean
@ConfigurationProperties(prefix = "serviceA")
public ServiceProperties serviceAProperties() {
return new ServiceProperties ();
}
@Bean
@ConfigurationProperties(prefix = "serviceB")
public ServiceProperties serviceBProperties() {
return new ServiceProperties ();
}
and at service(or someplace where will use properties) put a @Qualifier and specified which property would be auto wired .
public class ServiceA {
@Autowired
@Qualifier("serviceAProperties")
private ServiceProperties serviceAProperties;
}
Following this post Guide to @ConfigurationProperties in Spring Boot you can create a simple class without annotations:
public class ServiceProperties {
private String url;
private String port;
// Getters & Setters
}
And then create the @Configuration class using @Bean annotation:
@Configuration
@PropertySource("classpath:name_properties_file.properties")
public class ConfigProperties {
@Bean
@ConfigurationProperties(prefix = "serviceA")
public ServiceProperties serviceA() {
return new ServiceProperties ();
}
@Bean
@ConfigurationProperties(prefix = "serviceB")
public ServiceProperties serviceB(){
return new ServiceProperties ();
}
}
Finally you can get the properties as follow:
@SpringBootApplication
public class Application implements CommandLineRunner {
@Autowired
private ConfigProperties configProperties ;
private void watheverMethod() {
// For ServiceA properties
System.out.println(configProperties.serviceA().getUrl());
// For ServiceB properties
System.out.println(configProperties.serviceB().getPort());
}
}