서버

Spring boot3 - properties에 있는 환경변수를 bean으로 등록해 사용해보기

탐훈 2024. 11. 25. 12:37
728x90

1. properties에 환경변수 등록

 

currency에 관한 데이터를 환경변수로 등록하기

 

[application.properties]

spring.application.name=learn-spring-boot

logging.level.org.springframework=debug

spring.profiles.active=dev

currency-service.url=http://deafult.api.com
currency-service.username=tomhoon
currency-service.key=1234

 

[application-dev.properties]

spring.application.name=learn-spring-boot

logging.level.org.springframework=debug

currency-service.url=http://deafult-dev.api.com
currency-service.username=tony
currency-service.key=5678

 

[application-prod.properties]

spring.application.name=learn-spring-boot

logging.level.org.springframework=debug

currency-service.url=http://deafult-prod.api.com
currency-service.username=anthony
currency-service.key=9999

 


 

 

2. bean을 생성하여 context에 등록하기

 

 

[CurrencyServiceConfiguration.java]

package com.in28minutes.springboot.learn_spring_boot;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@ConfigurationProperties(prefix = "currency-service")
@Component
public class CurrencyServiceConfiguration {
    
    private String url;
    private String username;
    private String key;

    public String getUrl() {
        return this.url;
    }

    public String getUsername() {
        return this.username;
    }

    public String getKey() {
        return this.key;
    }

    public void setUrl(String url) {
        this.url = url;
    }

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

    public void setKey(String key) {
        this.key = key;
    }
}

 

 

3. 확인해보기

 

[TestController.java]

@RestController
public class TestController {

    @Autowired
    private CurrencyServiceConfiguration config;

    @RequestMapping("/test")
    public CurrencyServiceConfiguration test() {
        return config;
    }
    
}

 


application.properties에 

다른 환경을 설정하면 어떻게 될까?

 

prod로 바꿔보자

 

[application.properties]

spring.application.name=learn-spring-boot

logging.level.org.springframework=debug

spring.profiles.active=prod

currency-service.url=http://deafult.api.com
currency-service.username=tomhoon
currency-service.key=1234

 

 

 

prod로 바꿨더니

application-prod.properties 에 있는 환경변수를 가져온다.