繁体   English   中英

在 `@Bean` 方法上使用 `@ConfigurationProperties` 注释

[英]Using `@ConfigurationProperties` annotation on `@Bean` Method

有人可以提供有关如何直接在@Bean方法上使用@ConfigurationProperties注释的 MWE 吗?

我已经看到无数将它用于类定义的示例 - 但还没有用于@Bean方法的示例。

引用文档

  • 将此添加到类定义或@Bean方法中
  • @目标(值={类型,方法})

所以,我认为也有一种可能性和预期用途 - 但不幸的是我无法弄清楚。

spring.datasource.url = [url]
spring.datasource.username = [username]
spring.datasource.password = [password]
spring.datasource.driverClassName = oracle.jdbc.OracleDriver
@Bean
@ConfigurationProperties(prefix="spring.datasource")
public DataSource dataSource() {
    return new DataSource();
}

这里DataSource类有属性url、用户名、密码、driverClassName,所以spring boot将它们映射到创建的对象上。

DataSource 类的示例:

public class DataSource {
    private String url;
    private String driverClassName;
    private String username;
    private String password;
    //getters & setters, etc.
}

换句话说,这与使用构造型注释(@Component、@Service 等)初始化某个 bean 的效果相同,例如

@Component
@ConfigurationProperties(prefix="spring.datasource")
public class DataSource {
    private String url;
    private String driverClassName;
    private String username;
    private String password;
    //getters & setters, etc.
}

24.8.1 第三方配置

除了使用@ConfigurationProperties来注释一个类之外,您还可以在公共@Bean方法上使用它。 当您想要将属性绑定到您无法控制的第三方组件时,这样做会特别有用。

要从 Environment 属性配置 bean,请将@ConfigurationProperties添加到其 bean 注册中,如以下示例所示:

@ConfigurationProperties(prefix = "another")
@Bean
public AnotherComponent anotherComponent() {
    ...
}

使用 another 前缀定义的任何属性都以类似于前面的 AcmeProperties 示例的方式映射到该 AnotherComponent bean。

我找到了以下解决方案:即我们在应用程序 yaml 中有几个部分,我们在 appConfig 中很有趣:

  appConfig:
  version: 1.0_alpha
  environment: ${spring.profiles}
  dbDriver: ${spring.datasource.driver-class-name}
  dbUrl: ${spring.datasource.url}
  keyCloak:
      serverOne:
          host: http://xx.xx.xxx.xxx:8080
          baseUrl: ${appConfig.keyCloak.serverOne.host}/auth/realms/master
          clientId: api-service-agent
          clientSecret: f00955443-d123-4cfe-90d3-e3ff3b214aaffe
          serviceUsername: service-user
          servicePassword: 1234567890
      serverTwo:
          host: http://xx.xxx.xxx.xxx:8080
          baseUrl: ${appConfig.keyCloak.serverTwo.host}/auth/realms/wissance
          clientId: api-service-agent
          clientSecret: a20ddf0-56fa-4991-85bc-114377eeffddcc
          serviceUsername: service-user
          servicePassword: 1234567890
      using: 
          baseUrl: ${appConfig.keyCloak.serverTwo.baseUrl}
          clientId: ${appConfig.keyCloak.serverTwo.clientId}
          clientSecret: ${appConfig.keyCloak.serverTwo.clientSecret}
          serviceUsername: ${appConfig.keyCloak.serverTwo.serviceUsername}
          servicePassword: ${appConfig.keyCloak.serverTwo.servicePassword}

我们想拆分通用设置并使用 KeyCloak 设置,所以我实现了以下方案:

我制作了以下 KeyCloakConfig 类(没有 @ConfigurationProperties 注释)来使用身份验证服务器设置进行存储:

@Configuration
public class KeyCloakConfig {

    public KeyCloakConfig(){

    }

    public KeyCloakConfig(String baseUrl, String clientId, String clientSecret, String username, String password) {
        this.baseUrl = baseUrl;
        this.clientId = clientId;
        this.clientSecret = clientSecret;
        this.username = username;
        this.password = password;
    }

    public String getBaseUrl(){
        return baseUrl;
    }

    public void setBaseUrl(String baseUrl){
        this.baseUrl = baseUrl;
    }

    public String getClientId(){
        return clientId;
    }

    public void setClientId(String clientId){
        this.clientId = clientId;
    }

    public String getClientSecret(){
        return clientSecret;
    }

    public void setClientSecret(String clientSecret){
        this.clientSecret = clientSecret;
    }

    public String getUsername(){
        return username;
    }

    public void setUsername(String username){
        this.username = username;
    }

    public String getPassword(){
        return password;
    }

    public void setPassword(String password){
        this.password = password;
    }

    @Value("${appConfig.keyCloak.using.baseUrl}")
    private String baseUrl;

    @Value("${appConfig.keyCloak.using.clientId}")
    private String clientId;

    @Value("${appConfig.keyCloak.using.clientSecret}")
    private String clientSecret;

    @Value("${appConfig.keyCloak.using.serviceUsername}")
    private String username;

    @Value("${appConfig.keyCloak.using.servicePassword}")
    private String password;
}

和 AppConfig 类,它包含常用设置,如版本、使用 DB 驱动程序和 url 的环境以及 KeyCloakConfig 作为属性:

@Configuration
@EnableConfigurationProperties
@ConfigurationProperties
public class AppConfig {

public AppConfig(){

    }

    public AppConfig(String apiVersion, String environment, String databaseDriver, String databaseUrl){
        this.apiVersion = apiVersion;
        this.environment = environment;
        this.databaseDriver = databaseDriver;
        this.databaseUrl = databaseUrl;
    }

    public String getEnvironment(){
        return environment;
    }

    public void setEnvironment(String environment) {
        this.environment = environment;
    }

    public String getDatabaseDriver(){
        return databaseDriver;
    }

    public void setDatabaseDriver(String databaseDriver) {
        this.databaseDriver = databaseDriver;
    }

    public String getDatabaseUrl(){
        return databaseUrl;
    }

    public void setDatabaseUrl(String databaseUrl) {
        this.databaseUrl = databaseUrl;
    }

    public String getApiVersion(){
        return apiVersion;
    }

    public void setApiVersion(String apiVersion) {
        this.apiVersion = apiVersion;
    }

    public KeyCloakConfig getKeyCloakConfig(){
        return keyCloakConfig;
    }

    public void setKeyCloakConfig(KeyCloakConfig keyCloakConfig){
        this.keyCloakConfig = keyCloakConfig;
    }

    @Value("${appConfig.version}")
    private String apiVersion;

    @Value("${appConfig.environment}")
    private String environment;

    @Value("${appConfig.dbDriver}")
    private String databaseDriver;

    @Value("${appConfig.dbUrl}")
    private String databaseUrl;

    @Autowired
    private KeyCloakConfig keyCloakConfig;
}

您可以使用@ConfigurationProperties 如下

实体模型

public class MY_ENTITY {
    private String prop1;
    private String prop2;
    // setter & getter & toString()
}

豆方法

@Configuration
public class MyClass {

    @Bean
    @ConfigurationProperties(prefix = "my.entity")
    public MY_ENTITY getContract() {
        return new MY_ENTITY()
                .setProp1("prop1111111")
                .setProp2("prop2222222")
                ;
    }

    @Bean(name = "contract2")
    @ConfigurationProperties(prefix = "my.entity2")
    public MY_ENTITY getContract2() {
        return new MY_ENTITY()
                .setProp1("prop1111.2222")
                .setProp2("prop2222.222")
                ;
    }
}

应用程序属性

my.entity.prop1=2120180023
my.entity.prop2=CUSTOMER_NAME111

my.entity2.prop1=9994494949
my.entity2.prop2=CUSTOMER_NAME222

SpringBoot 应用程序

@SpringBootApplication
public class DemoApplication implements CommandLineRunner {

    @Autowired
    @Qualifier("contract2")
    private MY_ENTITY myEntity;

    public static void main(String[] args) throws Exception {
        SpringApplication.run(DemoApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        System.out.println(myEntity);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM