This example shows the use of @Conditional annotation on @Component classes used with @ComponentScan.
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.*;
import org.springframework.stereotype.Component;
import java.util.Locale;
@Configuration
@ComponentScan(basePackageClasses = BeanConditionScanExample.class,
useDefaultFilters = false,
includeFilters = {@ComponentScan.Filter(
type = FilterType.ASSIGNABLE_TYPE,
value = {BeanConditionScanExample.MyClientBean.class,
BeanConditionScanExample.ServiceBeanImpl1.class,
BeanConditionScanExample.ServiceBeanImpl2.class})})
public class BeanConditionScanExample {
public static void main(String[] args) {
runApp(Locale.US);
System.out.println("----------");
runApp(Locale.CANADA);
}
public static void runApp(Locale locale) {
System.out.printf("setting default locale: %s\n", locale);
Locale.setDefault(locale);
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(
BeanConditionScanExample.class);
MyClientBean bean = context.getBean(MyClientBean.class);
System.out.printf("Injected ServiceBean instance in MyClientBean: %s\n", bean.getServiceBean()
.getClass()
.getSimpleName());
}
@Component
public static class MyClientBean {
@Autowired
private ServiceBean serviceBean;
public ServiceBean getServiceBean() {
return serviceBean;
}
}
public interface ServiceBean {
}
@Component
@Conditional(LocaleConditionUSA.class)
public static class ServiceBeanImpl1 implements ServiceBean {
}
@Component
@Conditional(LocaleConditionCanada.class)
public static class ServiceBeanImpl2 implements ServiceBean {
}
}
Output
setting default locale: en_US
Injected ServiceBean instance in MyClientBean: ServiceBeanImpl1
----------
setting default locale: en_CA
Injected ServiceBean instance in MyClientBean: ServiceBeanImpl2
Original Post