Spring 提供了一个通用的基于条件来创建Bean
的注解@Conditional
注解。
通过实现Condition
接口,并重写其matches
方法来构造判断条件。
例如,根据操作系统返回对应的内容。
1. 定义判断条件
例如,根据操作系统返回对应的内容。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| import org.springframework.context.annotation.Condition; import org.springframework.context.annotation.ConditionContext; import org.springframework.core.type.AnnotatedTypeMetadata;
public class WindowsCondition implements Condition {
@Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { return context.getEnvironment().getProperty("os.name").contains("Windows"); } }
import org.springframework.context.annotation.Condition; import org.springframework.context.annotation.ConditionContext; import org.springframework.core.type.AnnotatedTypeMetadata;
public class LinuxCondition implements Condition {
@Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { return context.getEnvironment().getProperty("os.name").contains("Linux"); } }
|
2. 不同系统下的Bean类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| public interface ListService { public String showListCmd(); }
public class WindowsListServiceImpl implements ListService {
@Override public String showListCmd() { return "dir"; } }
public class LinuxListServiceImpl implements ListService {
@Override public String showListCmd() { return "ls"; } }
|
3. 定义配置类 Bean
**@Conditional()**注解调用条件判断的类并根据返回的结果来创建Bean
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Conditional; import org.springframework.context.annotation.Configuration;
@Configuration public class ConditionConfig { @Bean @Conditional(WindowsCondition.class) public ListService windowsListService() { return new WindowsListServiceImpl(); } @Bean @Conditional(LinuxCondition.class) public ListService linuxListService() { return new LinuxListServiceImpl(); } }
|
4. 注解生效使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class ConditionMain { public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ConditionConfig.class); ListService listService = context.getBean(ListService.class); System.out.println(context.getEnvironment().getProperty("os.name") + "系统下的列表命令:" + listService.showListCmd()); } }
|