해당 게시물은 백기선님의 스프링 프레임워크 핵심 기술 강좌를 정리한 내용 입니다.
1. 프로퍼티
- 프로퍼티는 다양한 방법으로 정의할 수 있는 설정 값이다.
- Environment의 역할은 프로퍼티 소스 설정 및 프로퍼티 값 가져오기
2. 프로퍼티 설정 방법
1) JVM 시스템 프로퍼티 (-Dkey=“value”)
-Dkey=value 형태로 환경 변수를 정의할 수 있다.
예를 들어, -Dapp.name=spring5 으로 설정한 다음, 이 값을 Environment 객체를 통해 받아올 수 있다.
@Component
public class AppRunner implements ApplicationRunner {
@Autowired
ApplicationContext ctx;
@Autowired
BookRepository bookRepository;
@Override
public void run(ApplicationArguments args) throws Exception {
Environment environment = ctx.getEnvironment();
System.out.println(environment.getProperty("app.name"));
}
}
좀 더 체계적으로 값을 전달 하고 싶다면 다음과 같이 할 수 있다.
2) @PropertySource
① resources에 app.propertis를 생성한다.
app.properties 파일에 아래와 같이 환경 변수를 설정 할 수 있다.
app.about=spring
② @Configuration이 있는 클래스에서 @PropertySource 애노테이션을 추가 한다.
@PropertySource 애노테이션에 properties의 경로를 전달하면 Environment 객체에 프로퍼티 값이 자동으로
주입된다.
@SpringBootApplication
@PropertySource("classpath:/app.properties")
public class Demospring51Application {
public static void main(String[] args) {
SpringApplication.run(Demospring51Application.class, args);
}
}
③ Runner에서 아래와 같이 확인 할 수 있다.
@Component
public class AppRunner implements ApplicationRunner {
@Autowired
ApplicationContext ctx;
@Autowired
BookRepository bookRepository;
@Override
public void run(ApplicationArguments args) throws Exception {
Environment environment = ctx.getEnvironment();
System.out.println(environment.getProperty("app.name"));
System.out.println(environment.getProperty("app.about"));
}
}
'Spring > Spring Core' 카테고리의 다른 글
[Section 1] IoC 컨테이너 8부: ApplicationEventPublisher (0) | 2020.09.06 |
---|---|
[Section 1] IoC 컨테이너 7부: MessageSource (0) | 2020.09.06 |
[Section 1] IoC 컨테이너 6부: Environment 1부. 프로파일 (0) | 2020.09.03 |
[Section 1] IoC 컨테이너 5부: 빈의 스코프(Scope) (0) | 2020.09.03 |
[Section 1] IoC 컨테이너 4부: @Component와 컴포넌트 스캔 (0) | 2020.09.03 |
댓글