spring 在“@Bean”方法上使用“@ConfigurationProperties”注解

0md85ypi  于 2023-02-18  发布在  Spring
关注(0)|答案(4)|浏览(168)

有人能给予如何在@Bean方法上直接使用@ConfigurationProperties注解的MWE吗?
我已经看到无数的例子,它被用于类定义-但还没有例子的@Bean方法。
引用documentation

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

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

goqiplq2

goqiplq21#

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、username、password、driverClassName,因此spring boot将它们Map到创建的对象。
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.
}
ehxuflar

ehxuflar2#

24.8.1第三方配置
除了使用@ConfigurationProperties来注解类,你还可以在公共@Bean方法上使用它,当你想把属性绑定到你控制之外的第三方组件时,这样做特别有用。
要通过Environment属性配置Bean,请将@ConfigurationProperties添加到其Bean注册中,如以下示例所示:

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

使用另一个前缀定义的任何属性都Map到AnotherComponent bean上,方式与前面的AcmeProperties示例类似。

v9tzhpje

v9tzhpje3#

我找到了以下解决方案:例如,我们在应用程序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;
}
qmb5sa22

qmb5sa224#

您可以按如下方式使用@ConfigurationProperties

实体模型

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

Bean方法

@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

Spring启动应用程序

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

相关问题