방카@Dev
[Spring]Spring Environment 본문
# 개요
- Spring Environment는 어플리케이션 내에서 프로필(Profiles)과 속성(Properties)을 유연하게 관리하기 위한 모델을 제공
- Spring Enviroment는 어플리케이션이 실행되는 다양한 환경(local, dev, prod)에 따라 빈(bean)과 속성을 구성할 수 있도록 하여 개발, 테스트, 프로덕션 등 다양한 환경에서 각기 다른 구성을 쉽게 관리할 수 있음
1. 프로필(Profile)
- 프로필은 코드에서 활성화된 프로필에 따라 컨테이너에 등록됨.
1) Annotation 사용
(1) dev 모드
package com.kbfg.digi;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
@Configuration
@Profile("dev")
public class ApplicationConfigDev {
@Bean
public ServerInfo serverInfo() {
ServerInfo serverInfo = new ServerInfo();
serverInfo.setIpNum("localhost");
serverInfo.setPortNum("9181");
return serverInfo;
}
}
(2) Run 모드
package com.kbfg.digi;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
@Configuration
@Profile("run")
public class ApplicationConfigRun {
@Bean
public ServerInfo serverInfo() {
ServerInfo serverInfo = new ServerInfo();
serverInfo.setIpNum("213.186.229.29");
serverInfo.setPortNum("80");
return serverInfo;
}
}
(3) Main 클래스
package com.kbfg.digi;
import java.util.Scanner;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class MainClass {
public static void main(String[] args) {
// TODO Auto-generated method stub
String config = null;
Scanner scanner = new Scanner(System.in);
String str = scanner.next();
if(str.equals("dev")) {
config="dev";
} else if(str.equals("run")) {
config = "run";
}
scanner.close();
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.getEnvironment().setActiveProfiles(config);
ctx.register(ApplicationConfigDev.class, ApplicationConfigRun.class);
ctx.refresh();
ServerInfo info = ctx.getBean("serverInfo",ServerInfo.class);
System.out.println("ip :"+ info.getIpNum());
System.out.println("port :"+info.getPortNum());
ctx.close();
}
}
2) XML 사용
- xml은 beans에 profile을 명시
(1) dev 모드
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"
profile="dev" //profile 입력
>
<bean id="serverInfo" class="com.kbfg.digi.ServerInfo">
<property name="ipNum" value="localhost"></property>
<property name="portNum" value="9181"></property>
</bean>
</beans>
(2) run 모드
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"
profile="run" //profile 입력
>
<bean id="serverInfo" class="com.kbfg.digi.ServerInfo">
<property name="ipNum" value="localhost"></property>
<property name="portNum" value="8181"></property>
</bean>
</beans>
(3) Main 클래스
package com.kbfg.digi;
import java.util.Scanner;
import org.springframework.context.support.GenericXmlApplicationContext;
public class MainClass {
public static void main(String[] args) {
// TODO Auto-generated method stub
String config = null;
Scanner scanner = new Scanner(System.in);
String str = scanner.next();
if(str.equals("dev")) {
config="dev";
} else if(str.equals("run")) {
config = "run";
}
scanner.close();
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
ctx.getEnvironment().setActiveProfiles(config);
ctx.load("applicationCTX_dev.xml","applicationCTX_run.xml");
ServerInfo info = ctx.getBean("serverInfo",ServerInfo.class);
System.out.println("ip :"+ info.getIpNum());
System.out.println("port :"+info.getPortNum());
}
}
2. *.properties 파일을 이용하는 경우
<admin.properties> ※ 위치 src/main/resources
admin.id = abcde
admin.pw = 12345
<sub_admin.properties> ※ 위치 src/main/resources
sub_admin.id = gunni
sub_admin.pw = 1234
1) Annotation 방법
package com.kbfg.digi;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
@Configuration
public class ApplicationConfig {
@Value("${admin.id}")
private String adminId;
@Value("${admin.pw}")
private String adminPw;
@Value("${sub_admin.id}")
private String sub_adminId;
@Value("${sub_admin.pw}")
private String sub_adminPw;
@Bean
public AdminConnection adminConfig(){
AdminConnection adminConnection = new AdminConnection();
adminConnection.setAdminId(adminId);
adminConnection.setAdminPw(adminPw);
adminConnection.setSub_adminId(sub_adminId);
adminConnection.setSub_adminPw(sub_adminPw);
return adminConnection;
}
@Bean
public static PropertySourcesPlaceholderConfigurer Properties() {
PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
Resource[] locations = new Resource[2];
locations[0] = new ClassPathResource("admin.properties"); //프로퍼티 파일 등록
locations[1] = new ClassPathResource("sub_admin.properties"); //프로퍼티 파일 등록
configurer.setLocations(locations);
return configurer;
}
}
package com.kbfg.digi;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
public class AdminConnection implements InitializingBean, DisposableBean {
private String adminId;
private String adminPw;
private String sub_adminId;
private String sub_adminPw;
@Override
public void destroy() throws Exception {
}
@Override
public void afterPropertiesSet() throws Exception {
}
public String getAdminId() {
return adminId;
}
public void setAdminId(String adminId) {
this.adminId = adminId;
}
public String getAdminPw() {
return adminPw;
}
public void setAdminPw(String adminPw) {
this.adminPw = adminPw;
}
public String getSub_adminId() {
return sub_adminId;
}
public void setSub_adminId(String sub_adminId) {
this.sub_adminId = sub_adminId;
}
public String getSub_adminPw() {
return sub_adminPw;
}
public void setSub_adminPw(String sub_adminPw) {
this.sub_adminPw = sub_adminPw;
}
}
package com.kbfg.digi;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class MainClass {
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ApplicationConfig.class);
AdminConnection connection = ctx.getBean("adminConfig", AdminConnection.class);
System.out.println("adminID : "+connection.getAdminId());
System.out.println("adminPw : "+connection.getAdminPw());
System.out.println("sub_adminID : "+connection.getSub_adminId());
System.out.println("sub_adminPW : "+connection.getSub_adminPw());
}
}
2) XML 사용 방법
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<context:property-placeholder location="classpath:admin.properties, classpath:sub_admin.properties"/> //프로퍼티 파일 등록
<bean id="adminConnection" class="com.kbfg.digi.AdminConnection">
<property name="adminId">
<value>${admin.id}</value>
</property>
<property name="adminPw">
<value>${admin.pw}</value>
</property>
<property name="sub_adminId">
<value>${sub_admin.id}</value>
</property>
<property name="sub_adminPw">
<value>${sub_admin.pw}</value>
</property>
</bean>
</beans>
package com.kbfg.digi;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
public class MainClass {
public static void main(String[] args) {
// TODO Auto-generated method stub
AbstractApplicationContext ctx = new GenericXmlApplicationContext("classpath:applicationCTX.xml");
AdminConnection connection = ctx.getBean("adminConnection", AdminConnection.class);
System.out.println("admin ID : "+connection.getAdminId());
System.out.println("admin Pw : "+connection.getAdminPw());
System.out.println("sub_admin ID : "+connection.getSub_adminId());
System.out.println("sub_admin pw : "+connection.getSub_adminPw());
ctx.close();
}
}
'BackEnd > Spring' 카테고리의 다른 글
[Spring]MVC에서 데이터를 주고 받는 방법 (0) | 2024.06.12 |
---|---|
[Spring]AOP(Aspect Oriented Programming)_스프링 핵심원리(고급편) (0) | 2024.06.11 |
[Spring]Bean 생성주기 (0) | 2024.06.10 |
[Spring]Ch9.데이터베이스:관리자 회원가입 기능 만들기_올인원 스프링 프레임워크 (1) | 2024.06.09 |
[Spring]web.xml에 한글깨짐현상 방지 filter 태그 추가하기 (0) | 2024.06.08 |