Search code examples
springspring-bootspring-config

Spring Boot: Multiple similar ConfigurationProperties with different Prefixes


I'm using Spring Boot and have two very similar services which I'd like to configure in my application.yml.

The configuration looks roughly like this:

serviceA.url=abc.com
serviceA.port=80

serviceB.url=def.com
serviceB.port=8080

Is it possible to create one class annotated with @ConfigurationProperties and set the prefix at the injection point?

e.g.

@Component
@ConfigurationProperties
public class ServiceProperties {
   private String url;
   private String port;

   // Getters & Setters
}

and then in the Services itself:

public class ServiceA {

   @Autowired
   @SomeFancyAnnotationToSetPrefix(prefix="serviceA")
   private ServiceProperties serviceAProperties;

   // ....
}

Unfortunately I haven't found something in the documentation about such a feature... Thank you very much for your help!


Solution

  • 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;
    
    }