http://ojc.asia/bbs/board.php?bo_table=LecSpring&wr_id=860
스프링에서 프로퍼티(Properety) 파일 다루기, @PropertySource, @Value
1. @PropertySource로 자바설정에서 프로퍼티 파일 다루기
@PropertySource는
- Spring의 환경(Environment)에 프로퍼티 파일의 속성을 주입하며,
- @Value를 통해 속성을 클래스 속성에 주입 할 수 있다.
[db1.properties]
jdbc.url=jdbc:oracle:thin:@localhost:1521:orcl
[Config.java]
@Configuration
// 자바8이상에서는 @PropertySource 여러 개 사용가능
@PropertySource(“classpath:db1.properties”)
@PropertySource(“classpath:db2.properties”)
// @PropertySources는 @PropertySource를 배열형태로 가진다.
@PropertySources({
@PropertySource(“classpath:db3.properties”),
@PropertySource(“classpath:db4.properties”)
})
public class Config {
@Autowired
private Environment env;
@Value(“${jdbc.url}”)
private String url;
// DB연결을 위한 데이터소스 정의
@Bean
public DataSource dataSource() {
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setUrl(env.getProperty("jdbc.url"));
dataSource.setUrl( url );
……
return dataSource;
}}
2. XML 파일에서 Property File 다루기
[스프링 설정파일]
// @PropertySource를 대신한 XML 설정
// 아래의 경우 자바설정(@Configuration)등에서
// Environment API를 사용할 수 없다.
<context:property-placeholder
location="classpath:db1.properties" />
<context:property-placeholder
location="classpath:db1.properties,
classpath:db2.properties" />
<bean id="dataSource">
<property name="url" value="${jdbc.url}" />
</bean>
3. 실습
File >> new >> project >> maven >> maven project
[pom.xml]
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>demo1</groupId>
<artifactId>demo1</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo1</name>
<description>demo1</description>
<properties>
<spring-version>5.2.3.RELEASE</spring-version>
</properties>
<dependencies>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring-version}</version>
</dependency>
</dependencies>
</project
[src/main/resources/application.properties]
# application.properties
app.name=Property Test Program
[AppConfig.java]
package demo1;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
// @PropertySource는 application.properties의 속성을 Spring의 환경에 주입.
@Configuration
@PropertySource(value = "application.properties", ignoreResourceNotFound = true)
public class AppConfig { }
[AppMain.java]
package demo1;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.core.env.Environment;
@ComponentScan(basePackages = "demo1")
public class AppMain {
private static final Logger logger = LoggerFactory.getLogger(AppMain.class);
// Spring 환경(Environment)을 주입
// env.getProperty()를 통해 속성값에 접근
@Autowired
private Environment env;
// @Value를 통해 application.properties의 속성값에 접근.
@Value("${app.name}")
private String appName;
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx =
new AnnotationConfigApplicationContext(AppMain.class);
AppMain app = ctx.getBean(AppMain.class);
app.run();
ctx.close();
}
private void run() {
logger.info("From Environment");
logger.info("app.name : {}", env.getProperty("app.name"));
logger.info("Using @Value injection");
logger.info("app.name : {}", appName);
}
}
[결과]
16:27:03.487 [main] INFO demo1.AppMain - From Environment
16:27:03.488 [main] INFO demo1.AppMain - app.name : Property Test Program
16:27:03.489 [main] INFO demo1.AppMain - Using @Value injection
16:27:03.489 [main] INFO demo1.AppMain - app.name : Property Test Program
#스프링프로퍼티, #스프링강좌, #스프링강의, #스프링교육, #Spring강의, #Sprint강좌, #스프링프레임워크, #스프링, #스프링동영상, #Spring동영상, #@PropertySource, #@Value
댓글 없음:
댓글 쓰기