programing

'@Bean' 메서드에서 '@ConfigurationProperties' 주석 사용

lovecodes 2023. 3. 26. 12:33
반응형

'@Bean' 메서드에서 '@ConfigurationProperties' 주석 사용

누가 MWE를 어떻게 사용하는 방법을 알려주실 수 있나요?@ConfigurationProperties직접 주석@Bean방법?

클래스 정의에 사용되는 예는 셀 수 없을 정도로 많지만 아직 예시는 없습니다.@Bean방법들.

문서를 인용하려면:

  • 클래스 정의 또는 메서드에 추가
  • @Target(값={)유형, 방법)

그래서 저는 가능성과 의도된 용도가 있다고 생각합니다만, 불행히도 그것을 이해할 수 없습니다.

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 클래스는 proeprties url, 사용자 이름, 비밀번호, driverClassName을 가지고 있으므로 스프링 부트는 이들을 생성된 객체에 매핑합니다.

DataSource 클래스의 예:

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

즉, 고정관념 주석(@Component, @Service 등)을 사용하여 빈을 초기화하는 것과 같은 효과가 있습니다.

@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다음 예시와 같이 빈 등록에 접속합니다.

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

다른 프레픽스로 정의된 속성은 위의 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}

KeyClock 설정을 사용하여 공통 설정을 분할하고 싶기 때문에 다음 방식을 구현했습니다.

인증 서버 설정을 사용하여 저장하는 다음 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()
}

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

application.properties

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

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

Spring Boot 어플리케이션

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

언급URL : https://stackoverflow.com/questions/43232021/using-configurationproperties-annotation-on-bean-method

반응형