@Profile

ํ”„๋กœํ•„๊ณผ ์™ธ๋ถ€ ์„ค์ •์„ ์‚ฌ์šฉํ•ด์„œ ๊ฐ ํ™˜๊ฒฝ๋งˆ๋‹ค ์„ค์ •๊ฐ’์„ ๋‹ค๋ฅด๊ฒŒ ์ ์šฉ์„ ํ•  ์ˆ˜ ์žˆ๋‹ค. ๊ทธ๋Ÿฐ๋ฐ ์„ค์ •๊ฐ’์€ ๋‹ค๋ฅธ ์ •๋„๊ฐ€ ์•„๋‹ˆ๋ผ ๊ฐ ํ™˜๊ฒฝ๋งˆ๋‹ค ์„œ๋กœ ๋‹ค๋ฅธ ๋นˆ์„ ๋“ฑ๋กํ•˜๋ ค๋ฉด ์–ด๋–ป๊ฒŒ ํ•ด์•ผํ• ๊นŒ? ์˜ˆ๋ฅผ ๋“ค์–ด ๊ฒฐ์ œ ๊ธฐ๋Šฅ์„ ๊ฐœ๋ฐœํ•˜๋Š”๋ฐ ๋กœ์ปฌ ๊ฐœ๋ฐœ ํ™˜๊ฒฝ์—์„œ๋Š” ๊ฐ€์งœ ๊ฒฐ์ œ ๊ธฐ๋Šฅ์„, ์šด์˜ ํ™˜๊ฒฝ์—์„œ๋Š” ์‹ค์ œ ๊ฒฐ์ œ ๊ธฐ๋Šฅ์„ ์ œ๊ณตํ•˜๋Š” ์Šคํ”„๋ง ๋นˆ์„ ๋“ฑ๋กํ•œ๋‹ค๊ณ  ํ•ด๋ณด์ž.

public interface PayClient {
    void pay(int money);
}
@Slf4j
public class LocalPayClient implements PayClient{
    @Override
    public void pay(int money) {
        log.info("๋กœ์ปฌ ๊ฒฐ์ œ money={}", money);
    }
}
@Slf4j
public class ProdPayClient implements PayClient{
    @Override
    public void pay(int money) {
      log.info("์šด์˜ ๊ฒฐ์ œ money={}", money);
    }
}
@Service
@RequiredArgsConstructor
public class OrderService {
    private final PayClient payClient;

    public void order(int money) {
        payClient.pay(money);
    }
}
@Slf4j
@Configuration
public class PayConfig {

    @Bean
    @Profile("default")
    public LocalPayClient localPayClient() {
        log.info("LocalPayClient ๋นˆ ๋“ฑ๋ก");
        return new LocalPayClient();
    }

    @Bean
    @Profile("prod")
    public ProdPayClient prodPayClient() {
        log.info("ProdPayClient ๋นˆ ๋“ฑ๋ก");
        return new ProdPayClient();
    }
}
  • @Profile ์–ด๋…ธํ…Œ์ด์…˜์„ ์‚ฌ์šฉํ•˜๋ฉด ํ•ด๋‹น ํ”„๋กœํ•„์ด ํ™œ์„ฑํ™”๋œ ๊ฒฝ์šฐ์—๋งŒ ๋นˆ์„ ๋“ฑ๋กํ•œ๋‹ค.

@Component
@RequiredArgsConstructor
public class OrderRunner implements ApplicationRunner {
    private final OrderService orderService;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        orderService.order(1000);
    }
}
  • ApplicationRunner์ธํ„ฐํŽ˜์ด์Šค๋ฅผ ๊ตฌํ˜„ํ•˜๋ฉด ์Šคํ”„๋ง์€ ๋นˆ ์ดˆ๊ธฐํ™”๊ฐ€ ๋ชจ๋‘ ๋๋‚˜๊ณ  ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜ ๋กœ๋”ฉ์ด ์™„๋ฃŒ๋˜๋Š” ์‹œ์ ์— run(args)๋ฉ”์„œ๋“œ๋ฅผ ํ˜ธ์ถœํ•ด์ค€๋‹ค.

@Profile ์ •์ฒด

...
@Conditional(ProfileCondition.class)
public @interface Profile {
	String[] value();
}

class ProfileCondition implements Condition {

    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        MultiValueMap<String, Object> attrs = metadata.getAllAnnotationAttributes(Profile.class.getName());
        if (attrs != null) {
            for (Object value : attrs.get("value")) {
                if (context.getEnvironment().acceptsProfiles(Profiles.of((String[]) value))) {
                    return true;
                }
            }
            return false;
        }
        return true;
    }

}
  • @Profile์€ ํŠน์ • ์กฐ๊ฑด์— ๋”ฐ๋ผ์„œ ํ•ด๋‹น ๋นˆ์„ ๋“ฑ๋กํ• ์ง€ ๋ง์ง€ ์„ ํƒํ•œ๋‹ค.

  • @Conditional ๊ธฐ๋Šฅ์„ ํ™œ์šฉํ•ด์„œ ๊ฐœ๋ฐœ์ž๊ฐ€ ํŽธ๋ฆฌํ•˜๊ฒŒ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋Š” @Profile ๊ธฐ๋Šฅ์„ ์ œ๊ณตํ•˜๋Š” ๊ฒƒ์ด๋‹ค.

Last updated