Spring(十三): Spring 条件注解 @Conditional

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
//Windows系统的判断条件
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");
}
}


//Linux系统的判断条件
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();
}

//Windows下的实现类
public class WindowsListServiceImpl implements ListService {

@Override
public String showListCmd() {
return "dir";
}
}

//Linux下的实现类
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());

//context.close();
}
}

Spring(十三): Spring 条件注解 @Conditional

http://blog.gxitsky.com/2018/04/11/Spring-13-condition/

作者

光星

发布于

2018-04-11

更新于

2022-06-17

许可协议

评论