<외부파일을 이용한 설정>
Environment 객체 이용하기
Environment 객체를 이용해 스프링 빈 설정을 한다.
Context 파일을 만들고, getEnvironmint() 로 객체를 가져온다.
env.getPropertySources(); 로 프로퍼티 소스를 가져온다.
프로퍼티 추가 및 추출
추가 : propertySources.addLast();
추출 : env.getProperty()
1 2 3 4 5 6 7 8 9 10 | ConfigurableApplicationContext ctx = new GenericXmlApplicationContext(); ConfigurableEnvironment env = ctx.getEnvironment(); MutablePropertySources propertySources = env.getPropertySources(); try{ propertySources.addLast(new ResourcePropertySource("class path:admin.properties")); System.out.println(env.getProperty("admin.id")); System.out.println(env.getProperty("admin.pw")); } | cs |
다음과 같이 이루어진다.
또한, 이 설정 값들을 빈 안에 넣을 수도 있다.
클래스에 EnvironmentAware 를 구현하면, setEnvironment(Environment env) 함수가 오버라이드 된다. 이 안에서 환경변수를 설정해준다. (초기화)
InitializeBean, DisposableBean 을 구현하여 오버라이드 하는 메소드에 위의 예처럼
환경변수의 admin.id, admin.pw 값을 초기화 시킨다.
그러면, 메인 클래스에서 빈 xml 파일을 추가함으로써 앞서 했던 것처럼 똑같이 활용할 수 있다.
Environment 객체 사용하지 않기 - xml
1 | <context:property-placeholder location="classpath:admin.properties, classpath:sub_admin.properties"/> | cs |
다음과 같이 외부파일을 가져오는 구문을, Xml 파일 안에 추가해 준다.
단, 이것을 사용하려면 beans 태그안에
1 2 3 | <beans xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd"> | cs |
를 추가해주어야 한다. 이건 외우기가 어려우니까, namespace 탭에 보면 context 등 추가할 수 있도록 체크박스로 이루어져 있으니까, 그걸로 쉽게 추가해주면 된다!
1 2 3 4 5 | <bean id="adminConnection" class="com.javalec.ex.Admin"> <property name="adminId"> <value>${admin.id}</value> </property> </bean> | cs |
그러면, 이와같이 값을 가져와서 빈을 설정할 수 있다.
Environment 객체 사용하지 않기 - Java Configuration 파일
java 파일에 어노테이션을 사용하여 빈을 만드는 방법이다.
1 2 | @Value("${admin.id}") private String adminId; | cs |
와 같은 형식으로 변수를 설정하고
1 2 3 4 5 6 7 8 9 10 11 12 | @Bean public static PropertySourcesPlaceholderConfigurer Properties(){ PropertySourcesPlaceholderConfigurer configured = new PropertySourcesPlaceholderConfigurer(); Resource[] locations = new Resource[2]; locations[0] = new ClassPathResource("admin.properties"); locations[1] = new ClassPathResource("sub_admin.properties"); configurer.setLocations(locations); return configure; } | cs |
이와같이 빈을 설정해준다.
프로파일 속성을 이용한 설정
1. 여러 개의 xml 파일을 만들어 놓는다. 동일한 아이디의 빈을 만들어 놓고 값은 다른 상태이다.
xml 의 beans 태그 안에
1 2 3 | <beans profile="지정할 아이디" > | cs |
다음과 같이 설정하면, profile의 안에 있는 아이디로 구분지어 빈을 활용할 수 있다.
GenericXmlApplicationContext 변수로
1 | ctx.getEnvironment().setActiveProfiles("지정한 아이디"); | cs |
아이디는 입력을 해서 받는, 초기화를 해주든 나름의 방법을 사용한다.
각 빈의 xml 파일안에 설정해준 profile 값과 똑같이 써주면 된다.
2. 자바파일을 이용해 빈을 만들 때는,
1 | @Profile("지정할 아이디") | cs |
위의 어노테이션을 써줌으로써 구분한다.
이는 os 에 따른 구분 혹은 상황에 따르게 다른 설정을 해주고 싶을 때, 구분하기 용이하다는 장점이 있다.
'JSP > 정리' 카테고리의 다른 글
[jsp/spring] DI (0) | 2017.02.03 |
---|---|
[jsp] Forwarding(포워딩) (0) | 2017.01.20 |
[jsp/개발방법론] FrontController 패턴 (0) | 2017.01.20 |
[jsp] JSTL (0) | 2017.01.20 |
[jsp] EL(Expression Language) (0) | 2017.01.19 |
댓글