본문 바로가기

Spring/Spring Boot

(SpringBoot) 외부설정(2)

외부 설정 중 같은 키의 값들을 묶어서 하나의 Bean으로 등록하는 방법

(타입-세이프 프로퍼티 @ConfigurationProperties )

 

외부 설정에 대한 정보를 Bean으로 등록하기 위한 클래스 파일 작성(getter, setter 사용)

key 값을 설정 : @ConfigurationPropertes(Key value); 

@ConfigurationProperties("choi")
public class ChoiProperties {
    private String name ;
    private int age;
    private String fullName;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getFullName() {
        return fullName;
    }

    public void setFullName(String fullName) {
        this.fullName = fullName;
    }
}

 

 

meta 정보를 생성하라는 알림이 생긴다.

 

 

 

 

빌드 시 meta 정보를 생성해주는 plugin 

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>

 

Bean으로 등록

@EnableConfigurationProperties(ChoiProperties.class)

원래는 해당 클래스의 프로퍼티를 사용하겠다는 위의 애노테이션을 추가해야 하지만 

이미 스프링에 내장되어있다.

단지 해당 클래스를 Bean으로 등록하기만 하면 된다.

 

@Component
@ConfigurationProperties("choi")
public class ChoiProperties {
    private String name ;
    private int age;
    private String fullName;

 

@Autowired 사용해서 코드 수정

@Component
public class SampleListener implements ApplicationRunner {
    
    @Autowired
    ChoiProperties choiProperties;
    
    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("===========================");
        System.out.println(choiProperties.getName());
        System.out.println(choiProperties.getAge());;
        System.out.println("===========================");
    }
}

실행결과

Third-party ConfigurationProperties

외부의 jar파일이나 다른 써드파티에 저장된 값에는 @ConfigurationProperties를 설정할 수 없기에 

직접 Bean으로 등록해준다.

@Bean
@ConfigurationProperties("server")
public ServerProperties serverProperties () {
    return new ServerProperties();
}

 

 

 

'Spring > Spring Boot' 카테고리의 다른 글

(SpringBoot) Logging  (0) 2020.01.05
(SpringBoot) 프로파일  (0) 2020.01.05
(SpringBoot) 외부설정(1)  (0) 2020.01.04
(SpringBoot) SpringApplication(2)  (0) 2020.01.03
(SpringBoot) SpringApplication(1)  (0) 2020.01.02