프로그래밍/Spring

[Spring] 스프링 Properties 관리하기

Jay Tech 2018. 11. 13. 21:19
반응형
* 스프링 Properties 정의하기

스프링 resource폴더 안에 datasource.properties를 정의해주고 그 안에 값들을 정의해 준다.




이 값들은 java config인 annotation으로 가져올 수 있다.


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
@Configuration
@PropertySource("classpath:datasource.properties")
public class PropertyConfig {
 
    @Value("${jay.username}")
    String user;
 
    @Value("${jay.password}")
    String password;
 
    @Value("${jay.dburl}")
    String url;
 
    @Bean
    public FakeDataSource fakeDataSource() {
        FakeDataSource fakeDataSource = new FakeDataSource();
        fakeDataSource.setUser(user);
        fakeDataSource.setPassword(password);
        fakeDataSource.setUrl(url);
        return fakeDataSource;
    }
 
    @Bean
    public static PropertySourcesPlaceholderConfigurer properties() {
        PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer();
        return propertySourcesPlaceholderConfigurer;
    }
}
 
cs



@Value 로 접근하여 가져온다. FakeDataSource는 그냥 저 user, password, url 이 들어있는 단순한 모델이다. 이런식으로 가져올 수 있다. 



* 스프링 환경 변수 설정하기


인텔리제이에서 EditConfiguration에 들어가면 환경 변수라는 것을 설정할 수 있다.





여기서 Environment variables에 값을 넣어주고 


아까 PropertyConfig 클래스에서 


1
2
@Autowired
Environment env;
cs
\

를 넣어주고 


1
fakeDataSource.setUser(env.getProperty("USERNAME")); // system property 사용
cs


이런식으로 해주면 시스템 프로퍼티가 사용가능하다. url이나 id, pw를 넣어야할 때 이런식으로 넣어줄 수 있다.


* 여러개의 properties정의하기.


1
@PropertySource({"classpath:datasource.properties""classpath:jms.properties"})
cs


이런식으로 해주면 여러 프로퍼티에서 가져올 수 있다. 혹은


1
2
3
4
@PropertySources({
        @PropertySource("classpath:datasource.properties"),
        @PropertySource("classpath:jms.properties")
})
cs


@PropertySources로 더 눈이 편하게 만들 수 있다. 이게 좀 더보기 편한 구조라고 하는데 음.. 쓰기 나름이겠지만 난 첫번 째가 더 간단해 보인다.


* Spring Boot 에서의 property 설정


맨 첫 번째 사진에서 application.properties에 정의를 해주고  @PropertySource태그를 전부 지워준다.  Spring Boot를 쓴다면 이게 더 간단한 방법이다. 






반응형