본문 바로가기

Spring

Spring 외부 설정 Property

환경에 따라 설정정보가 변경되는 경우가 생긴다면 외부 프로퍼티 파일에 저장된 정보를 유용하게 사용할 수 있다.

예를 들어 각 운영 환경에서 사용되는 DB가 다르면 각 환경에 맞도록 매번 수정하지 않고 프로퍼티를 설정하여 사용함으로서 

유지보수성을 향상시킬수 있다.

 

 

> Environment

 

db.properties

db.driver=com.mysql.Driver
db.jdbcUrl=jdbc:mysql://host/test
db.user=hak
db.password=1111

 

설정을 외부에 존재하는 파일에서 가져온다. 수정시에도 외부파일을 수정하면 된다.

 

MainByEnvXml.java

public class MainByEnvXml {

	public static void main(String[] args) throws IOException {
		
		GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
		ConfigurableEnvironment env = ctx.getEnvironment();
		MutablePropertySources propSources = env.getPropertySources();
		propSources.addLast(new ResourcePropertySource("classpath:/db.properties"));
		String dbUser = env.getProperty("db.user");
		System.out.printf("dbUser is %s\n", dbUser);
	}

}

ConfigurableEnvironment env = ctx.getEnvironment(); 로 Environment 객체를 가져오고,

MutablePropertySources propSources = env.getPropertySources(); 프로퍼티 파일을 가져온다.

그다음 addLast로 프로퍼티 파일을 추가해준다음 간단하게 dbUser를 출력해봤다.

 

위의 내용에 몇 가지만 추가하여 자바로 설정해본다.

 

Main01ByEnvJava.java

public class MainByEnvJava {

	public static void main(String[] args) throws IOException {
		
		AnnotationConfigApplicationContext ctx = 
				new AnnotationConfigApplicationContext();
		ctx.register(ConfigByEnv.class);
		ctx.refresh();
		ConfigurableEnvironment env = ctx.getEnvironment();
		String javaVersion = env.getProperty("java.version");
		String dbUser = env.getProperty("db.user");
		System.out.printf("java version is %s\n", javaVersion);
		System.out.printf("dbUser is %s\n", dbUser);
		ctx.close();
	}
}

ConfigByEnv를 빈으로 등록하고, 자바버전을 추가로 출력한다.

 

 

ConnectionProvider.java

public interface ConnectionProvider {
	public Connection getConnection();
}

 

JdbcConnectionProvider.java

public class JdbcConnectionProvider implements ConnectionProvider{
	
	private String driver;
	private String user;
	private String password;
	private String url;
	public void init() {
		System.out.printf("초기화 함 [%s, %s, %s, %s]\n",driver,url,user,password);
	}
	@Override
	public Connection getConnection() {
		// TODO Auto-generated method stub
		System.out.println("JdbcConnectionProvider: "+url+"연결 생성");
		return null;
	}
	public String getDriver() {
		return driver;
	}
	public void setDriver(String driver) {
		this.driver = driver;
	}
	public String getUser() {
		return user;
	}
	public void setUser(String user) {
		this.user = user;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getUrl() {
		return url;
	}
	public void setUrl(String url) {
		this.url = url;
	}
	
}

ConnectionProvider.java 인터페이스를 implements한다.

setter/getter와 테스트용 init()을 만들고, getConnection을 오버라이딩(재정의) 해줬다.

 

 

 

ConfigByEnv.java

@Configuration
@PropertySources(@PropertySource("classpath:/db.properties"))
public class ConfigByEnv {
	@Autowired
	private Environment env;
	@Bean(initMethod="init")
	public ConnectionProvider connectionProvider() {
		JdbcConnectionProvider connectionProvider = new JdbcConnectionProvider();
		connectionProvider.setDriver(env.getProperty("db.driver"));
		connectionProvider.setUrl(env.getProperty("db.jdbcUrl"));
		connectionProvider.setUser(env.getProperty("db.user"));
		connectionProvider.setPassword(env.getProperty("db.Password"));
		return connectionProvider;
	}
}

로드하려는 파일들을 @PropertySources(@PropertySource(~))로 선언한다. 

init을 걸어주고 set해줬다.

 

init메서드가 실행되고 자바버전과 유저가 출력된걸 볼 수 있다.

 

 

 

> PropertySourcesPlaceholderConfigurer

Environment객체를 이용했던 예제와 같은 내용을 테스트 해본다.

 

 

MainByPropOfJava.java

public class MainByPropOfJava {

	public static void main(String[] args) throws IOException {
		
		AnnotationConfigApplicationContext ctx = new
		AnnotationConfigApplicationContext(ConfigByProp.class);
		ctx.close();
	}

}

메인에서 AnnotationConfigApplicationContext를 사용하여 @Configuration이 붙은 ConfigByProp.java의 클래스를 

설정정보로 사용한다.

 

ConfigByProp.java

@Configuration
public class ConfigByProp {
	@Value("${db.driver}")
	private String driver;
	@Value("${db.jdbcUrl}")
	private String jdbcUrl;
	@Value("${db.user}")
	private String user;
	@Value("${db.password}")
	private String password;
	
	@Bean
	public static PropertySourcesPlaceholderConfigurer properties() {
		PropertySourcesPlaceholderConfigurer configurer =
				new PropertySourcesPlaceholderConfigurer();
		configurer.setLocation(new ClassPathResource("db.properties"));
		return configurer;
	}
	
	@Bean(initMethod="init")
	public ConnectionProvider connectionProvider() {
		JdbcConnectionProvider connectionProvider =
				new JdbcConnectionProvider();
		connectionProvider.setDriver(driver);
		connectionProvider.setUrl(jdbcUrl);
		connectionProvider.setUser(user);
		connectionProvider.setPassword(password);
		return connectionProvider;
	}
}

@Value로 값을 가져올 수 있고 '${프로퍼티 이름}' 형식으로 프로퍼티 값을 사용할 수 있다.

PropertySourcesPlaceholderConfigurer 클래스를 빈으로 등록하여 setLocation으로 프로퍼티를 설정한다.

 

 

 

 

> context:property-placeholder

 

MainByPropOfXml.java

public class MainByPropOfXml {

	public static void main(String[] args) throws IOException {
		
		GenericXmlApplicationContext ctx = 
				new GenericXmlApplicationContext("classpath:/db-config.xml");
		ctx.close();
	}

}

GenericXmlApplicationContext로 xml파일을 설정파일로 사용한다.

 

 

db-config.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 
   https://www.springframework.org/schema/beans/spring-beans.xsd
   http://www.springframework.org/schema/context 
   https://www.springframework.org/schema/context/spring-context.xsd">
	
	<context:property-placeholder location="classpath:/db.properties"/>
	<bean id="connProvider" class="main.JdbcConnectionProvider"
		init-method="init">
		<property name="driver" value="${db.driver}"/>
		<property name="url" value="${db.jdbcUrl}"/>
		<property name="user" value="${db.user}"/>
		<property name="password" value="${db.password}"/>	
	</bean>
</beans>

xml파일에서 <context:property-placeholder location="classpath:/db.properties"/>를 통해 같은 기능을 수행할 수 있다.

 

728x90
반응형