스프링 레시피 CH2.11 스프링 환경 및 프로파일마다 다른 POJO 로드하기

2023. 12. 17. 15:45카테고리 없음

과제

동일한 POJO 인스턴스/빈을 여러 애플리케이션 시나리오별로 초깃값들 달리하여 구성하라

해결책

자바 구성 클래스를 여러 개 만들고 각 클래스마다 POJO 인스턴/빈을 묶는다.

이렇게 묶은 의도를 잘 표현할 수 있게 프로파일을 명명하고 자바 구성 클래스에 @Profile을 붙인다.

풀이

자바 구성 클래스를 여러 개 두고 각각 상이한 POJO를 구성한 다음 애플리케이션 컨텍스트가 시나리오에 맞는 구성 클래스 파일을 읽어들여 실행하게 한다.

 

2.11.1 @Profile로 자바 구성 클래스를 프로파일별로 작성하기

@Configuration
@Profile("global")
@ComponentScan("com.spring.study.chapter02.shop")
public class ShopConfigurationGlobal {

    @Value("classpath:banner.txt")
    private Resource banner;

    @Bean(initMethod = "openFile", destroyMethod = "closeFile")
    public Cashier cashier() {
        final String path = System.getProperty("java.io.tmpdir") + "cashier";
        Cashier c1 = new Cashier();
        c1.setFileName("checkout");
        c1.setPath(path);
        return c1;
    }
}

 

@Configuration
@Profile({"summer", "winter"})
@ComponentScan("com.spring.study.chapter02.shop")
public class ShopConfigurationSumWin {

    @Bean
    public Product aaa() {
        Battery p1 = new Battery();
        p1.setName("AAA");
        p1.setPrice(2.0);
        p1.setRechargeable(true);
        return p1;
    }

    @Bean
    public Product cdrw() {
        Disc p2 = new Disc("CD-RW", 1.0);
        p2.setCapacity(700);
        return p2;
    }

    @Bean
    public Product dvdrw() {
        Disc p2 = new Disc("DVD-RW", 2.5);
        p2.setCapacity(700);
        return p2;
    }
}

 

@Profile은 클래스 레벨로 붙였기 때문에 자바 구성 클래스에 속한 모든 @Bean 인스턴스는 해당 프로파일로 편입된다.

 

 

2.11.2 프로파일 환경에 로드하기

프로파일에 속한 빈을 애플리케이션에 로드하려면 일단 프로파일을 활성화 한다.

프로파일 여러개를 한 번에 로드하는 것도 가능하면 자바 런타임 플래그나 WAR 파일 초기화 매개변수를 지정해 프로그램 방식으로 프로파일을 로드할 수도 있다.

 

1.프로그램 방식으로 프로파일을 로드하려면 먼저 컨텍스트 환경을 가져와 setActiveProfiles() 메서드를 호출한다.

public static void main(String[] args) {
    AnnotationConfigApplicationContext context =
            new AnnotationConfigApplicationContext();

    context.getEnvironment().setActiveProfiles("global", "winter");
    context.scan("com.spring.study.chapter02.shop");
    context.refresh();
}

 

2.자바 런타임 플래그 로드

-Dspring.profiles.active=global,winter