SPRING
스프링 Properties 관련 정리
JUMP개발자
2020. 4. 15. 14:24
프로퍼티
- 다양한 방법으로 정의할 수 있는 설정 값
- Environment는 properties source 설정과 properties value를 가져오는 역할을 한다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
package com.example.demo;
import org.springframework.context.annotation.PropertySource;
@SpringBootApplication
@PropertySource("classpath:/app.properties")
public class Demo1Application {
public static void main(String[] args) {
SpringApplication.run(Demo1Application.class, args);
}
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
|
아래와 같이 @PropertySource 어노테이션을 이용하여 app.properties 위치를 넣어주면, Environment 객체에 프로퍼티 값이 주입된다.
이떄 Root 경로는 src/main/resources가 잡힌다.
1. @Value 를 이용하면 아래와 같이 Property 값을 가져올 수 있다.
2. Envornment 객체의 getProperty 메서드를 이용하는 방법을 사용해도 된다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
package com.example.demo;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
@Component
public class AppRunner implements ApplicationRunner {
@Autowired
ApplicationContext ctx;
@Autowired
BookRepository bookRepository;
@Value("${app.name}")
String appName;
@Override
public void run(ApplicationArguments args) throws Exception {
// TODO Auto-generated method stub
Environment environment = ctx.getEnvironment();
System.out.println(appName);
}
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
|
두 경우 모두 application.properties 에 선언한 app.name의 value 값이 찍힌다.