Spring Boot:具有不同前缀的多个类似ConfigurationProperty

nio*_*ioe 6 spring spring-boot spring-config

我正在使用Spring Boot,并有两个非常相似的服务,我想在其中配置application.yml

配置大致如下所示:

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

serviceB.url=def.com
serviceB.port=8080
Run Code Online (Sandbox Code Playgroud)

是否可以创建一个注有注释的类@ConfigurationProperties并在注入点设置前缀?

例如

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

   // Getters & Setters
}
Run Code Online (Sandbox Code Playgroud)

然后在服务本身中:

public class ServiceA {

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

   // ....
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,我没有在文档中找到有关此功能的任何信息...非常感谢您的帮助!

Jav*_*ano 10

我完成了您尝试的几乎相同的操作。首先,注册每个属性bean。

@Bean
@ConfigurationProperties(prefix = "serviceA")
public ServiceProperties  serviceAProperties() {
    return new ServiceProperties ();
}

@Bean
@ConfigurationProperties(prefix = "serviceB")
public ServiceProperties  serviceBProperties() {
    return new ServiceProperties ();
}
Run Code Online (Sandbox Code Playgroud)

并在服务中(或将使用属性的地方)放置@Qualifier并指定将自动连线的属性。

public class ServiceA {
    @Autowired
    @Qualifier("serviceAProperties")
    private ServiceProperties serviceAProperties;

}
Run Code Online (Sandbox Code Playgroud)

  • 我正在尝试使用相同的方法,但我得到的 bean 的所有属性都设置为 null。我错过了什么? (6认同)

Jai*_*nez 5

按照这篇Spring Boot 中的@ConfigurationProperties 指南,您可以创建一个没有注释的简单类:

public class ServiceProperties {
   private String url;
   private String port;

   // Getters & Setters
}
Run Code Online (Sandbox Code Playgroud)

然后使用@Bean注解创建@Configuration类:

@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 ();
    }
}
Run Code Online (Sandbox Code Playgroud)

最后你可以得到如下属性:

@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());
    }
}
Run Code Online (Sandbox Code Playgroud)