Spring

[Spring] 예제로 보는 Environment Abstraction

KEMON 2020. 5. 27. 01:03
728x90

1. @Profile

어플리케이션 배포할 때 어느 상황에 맞춰서 DB를 붙여야하는데 이럴때 @Profile사용하면 좋다.

보통 @Configuration과 같이쓰인다.

@Configuration
@Profile("default")
public class AppDefaultConfig {
	@Bean(initMethod = "init", destroyMethod = "destroy")
    public Connection connection(ConnectionFactory connectionFactory){
        return connectionFactory.getConnection();
    }
}
@Configuration
@Profile("dev")
public class AppDefaultConfig {
	@Bean(initMethod = "init", destroyMethod = "destroy")
    public Connection connection(ConnectionFactory connectionFactory){
        return connectionFactory.getConnection();
    }
}

Run/Debug Configurations의 VM options 설정

※Run/Debug Configurations의 VM options의 설정에 맞는 @Profile의 이름이 실행된다.

-Dspring.profiles.active=default    →   @Profile("default")

-Dspring.profiles.active=dev   →   @Profile("dev")

 

※Run/Debug Configurations의 VM options 설정이 없을 때에는 default가 기본으로 설정되어 있다.

 

2. @PropertySource

특정 property의 요소를 사용할 수 있다.

jdbc.driver-name=org.h2.Driver
jdbc.url=jdbc:h2:mem:test;MODE=MySQL;
jdbc.username=sa
jdbc.password=

↑ application.properties가 위처럼 설정되어 있을 때

@Configuration
@Profile("default")
@PropertySource("classpath:application.properties")
public class AppDefaultConfig {
	@Bean(initMethod = "init", destroyMethod = "destroy")
    public ConnectionFactory connectionFactory(
            @Value("${jdbc.driver-name}") String driverClass,
            @Value("${jdbc.url}") String url,
            @Value("${jdbc.username}") String username,
            @Value("${jdbc.password}") String password
            ){
        return new ConnectionFactory(driverClass,url,username,password);
    }
}

@Value를 사용하여 property값을 사용할 수 있다.

728x90