프로파일

오진현·2023년 3월 23일
0

Spring

목록 보기
6/7

@Profile로 Bean 설정

BaseConfig.class

@Profile("prod")
@Configuration
public class BaseConfig {

    @Bean
    public String hello(){
        return "hello";
    }

}

TestConfig.class

@Profile("test")
@Configuration
public class TestConfig {

    @Bean
    public String hello(){
        return "test";
    }
}

ApplicationRunner.class

@Component
public class ApplicationRunner implements ApplicationRunner {
    @Autowired
    private String hello;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("==========");
        System.out.println(hello);
        System.out.println("==========");
}

1. application.properies에서 원하는 profile 설정

application.properies

spring.profiles.active=prod

spring.profiles.active=prod로 설정했기 때문에 BaseConfig.class 가 적용됨

결과:

2. 외부에서 jar 실행시 profile 설정

java -jar target/DeanApplication-0.0.1-SNAPSHOT.jar --spring.profile.active=test
결과 :

command Line arguments 가 우선순위가 높다.

profile 용 properties 분리

application-{profile}.properties의 우선순위가
application.properties 보다 높다.

AplicationRunner.class

@Component
public class ApplicationRunner implements org.springframework.boot.ApplicationRunner {

    @Autowired
    DeanProperties deanProperties;

    @Autowired
    private String hello;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("==========");
        System.out.println(hello);
        System.out.println("name-property :" + deanProperties.getName());
        System.out.println("==========");

DeanProperties.class

@Getter
@Setter
@Component
@ConfigurationProperties("dean")
public class DeanProperties {

    private String name;
    private int age;
    private String fullname;

}

아무런 profile 정보 없이 실행시

기존 application.properties 가 실행되는데, 이때 spring.profiles.active=prod 의 prod 설정이 application-prod.properties를 불러옴.

application.properties

dean.name = dean
dean.age = ${random.int(0,100)}
dean.fullname = ${dean.name} Oh
spring.profiles.active=prod

application-prod.properties

dean.name= dean prod

application-test.properties

dean.name= dean test

java -jar target/DeanApplication-0.0.1-SNAPSHOT.jar
실행결과

profile 설정 실행 방법

1. Command Arguments

java -jar target/DeanApplication-0.0.1-SNAPSHOT.jar --spring.profiles.active=test

2. IDE 설정

spring.profile.inclue로 다른 파일을 포함 할 수도 있음

profile
s나야

0개의 댓글