@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