개발 소발/개발 Spring
Spring Environment 기초 사용방법
우기!
2020. 7. 13. 09:13
Environment
Application Context은 Bean Factory기능만 하는게 아니다.
Application Context의 기능은 여러가지가 있다.
그 중하나가 Environment이다.(환경설정)
Environment 프로파일(Profile)
프로파일이란 Bean들의 묶음 특정 Bean들을 묶어 사용할때 유용하다.
@Profile로 ComponentScan으로 등록할 수 있고
@Repository
@Profile("!prod")//ComponentScan에 등록하기
public class TestBookRepository implements BookRepository{
@PostConstruct
@Override
public void run() {
System.out.println("TestBookRepository 생성");
}
}
@Configuration을 통해 Class형식으로 등록할 수있다
//profile정하고 class로 등록하는방법
@Configuration
@Profile("test")//test profile일때만 사용
public class TestConfiguration {
@Bean
public BookRepository bookRepository(){
return new TestBookRepository();
}
}
또 특정 profile만 실행하는 것이 아닌 특정 프로파일이 아닐때도 사용가능하다. !not 사용
prod Profile이 아닐때 예제코드
@Repository
@Profile("!prod")//ComponentScan에 등록하기
public class TestBookRepository implements BookRepository{
@PostConstruct
@Override
public void run() {
System.out.println("TestBookRepository 생성");
}
}
environment를 통해 properties 사용하기
Configuraion에 VMoption을 등록하거나
resources 경로 아래 Properties 파일을 생성하고
스프링시작부분에 @PropertySource("classpath:./App.Properties”)를 등록하고
꺼내올 수 있다.
@SpringBootApplication
@PropertySource("classpath:./App.Properties")
public class EnvironApplication {
public static void main(String[] args) {
SpringApplication.run(EnvironApplication.class, args);
}
}