-
외부 설정과 프로파일 (스프링 부트 활용 - 3)Programming/Spring Boot 2020. 3. 9. 17:18728x90
1. 외부 설정
테스트를 실행할 때 먼저 실제 코드에 있는 것들을 클래스 패스(main/java, main/resources 디렉토리)로 등록하고 빌드,
이후 테스트 코드 부분이 등록(test/java, test/resources)되고 빌드됨
따라서, 테스트 application.properties 에 사용하고자 하는 것이 없으면 에러남
->
1. 테스트 코드의 application.properties에 없는 것들 추가하기
2. 테스트 코드의 application.properties 삭제하기
3. 이름을 마음대로 지정하고(test.properties), 소스코드 내에서 등록하기
@TestPropertySource(locations = "classpath:/test.properties")
- 프로퍼티 우선순위, application.properties는 pdf 파일 확인
- 랜덤 값 설정하기
hongchan.age=${random.int}
- 플레이스 홀더
hongchan.name=hongchan hongchan.fullname=${hongchan.name} Yun
- 여러 연관성 있는 프로퍼티를 빈으로 관리하기
@Value는 아주 정확하게 써야 함!, 메타 정보를 제공해주지 않음
따라서 이런 식으로 사용하는 것이 좋음 (AppProperties, app.name ... )
hongchan.name = hongchan hongchan.age = ${random.int} hongchan.fullName = ${hongchan.name} Yun
@Component @ConfigurationProperties("hongchan") public class HongchanProperties { 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; } }
@Component public class SampleRunner implements ApplicationRunner { @Autowired HongchanProperties hongchanProperties; @Override public void run(ApplicationArguments args) throws Exception { System.out.println(hongchanProperties.getName()); System.out.println(hongchanProperties.getAge()); System.out.println(hongchanProperties.getFullName()); } }
- 프로퍼티 값을 검증할 수 있음
@Component @ConfigurationProperties("hongchan") @Validated public class HongchanProperties { @NotEmpty private String name; ... }
2. 프로파일
- 프로파일? 빈들의 묶음
- 어떤 특정한 프로파일에서만 빈을 등록하고 싶은 경우
- 다른 프로파일에서는 다른 빈을 등록하고 싶은 경우
@Profile("test") @Configuration public class TestConfiguration { @Bean public String hello() { return "hello test"; } }
@Component public class SampleRunner implements ApplicationRunner { @Autowired private String hello; @Override public void run(ApplicationArguments args) throws Exception { System.out.println(hello); } }
spring.profiles.active=test // 어떤 프로파일을 활성화 할 것인가? spring.profiles.include=prod // 어떤 프로파일을 추가할 것인가?
- 프로파일용 프로퍼티
각 프로파일에 해당하는 프로퍼티 정의 이때, 프로파일 프로퍼티가 application.properties보다 우선순위 높음
인프런 백기선님 '스프링 부트’ 강의를 듣고 정리한 내용입니다.
728x90'Programming > Spring Boot' 카테고리의 다른 글
스프링 웹 MVC - 2 (스프링 부트 활용 - 6) (0) 2020.03.10 스프링 웹 MVC - 1 (스프링 부트 활용 - 5) (0) 2020.03.10 로깅, 테스트, Devtools (스프링 부트 활용 - 4) (0) 2020.03.09 내장 웹 서버와 응용 (스프링 부트 원리 - 2) (0) 2020.03.08 의존성 관리와 자동설정 (스프링 부트 원리 - 1) (0) 2020.03.06