Spring Boot: Multiple similar ConfigurationProperties with different Prefixes

后端 未结 4 1001
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-29 07:45

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:

4条回答
  •  佛祖请我去吃肉
    2020-12-29 08:27

    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());
        }
    }
    

提交回复
热议问题