Java代码片段随机
JAVA SE系列
1. 判断一个字符串是否是一个有效的罗马数字
1 | // 正则 |
2. 判断一个数是否是2的整数次幂
1 | private static boolean isPowerOfTwo(int val) { |
Spring 生态
1. 使用代码方式,根据条件动态排除spring boot的自动装配
实现
EnvironmentPostProcessor
接口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
28
29
30
31
32
33
34public class ExcludeEnvironmentPostProcessor implements EnvironmentPostProcessor {
private static final Logger LOGGER = LoggerFactory.getLogger(ExcludeEnvironmentPostProcessor.class);
private static final String CONDITION_KEY = "exclude.activemq";
private static final String SPRING_EXCLUDE_KEY = "spring.autoconfigure.exclude";
private static final String[] CUSTOM_EXCLUDES = {"org.springframework.boot.autoconfigure.jms.activemq.ActiveMQAutoConfiguration"};
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
// 拿到条件
String condition = environment.getProperty(CONDITION_KEY);
if (!Boolean.parseBoolean(condition)) {
return;
}
// 排除掉 activemq 自动装配
Binder binder = Binder.get(environment);
List<String> targetExcludes = new ArrayList<>();
// org.springframework.boot.autoconfigure.AutoConfigurationImportSelector.getExcludeAutoConfigurationsProperty
List<String> oldExcludes = binder.bind(SPRING_EXCLUDE_KEY, String[].class).map(Arrays::asList).orElse(Collections.emptyList());
// 原来排除的
targetExcludes.addAll(oldExcludes);
// 新增需要排除的
targetExcludes.addAll(Arrays.asList(CUSTOM_EXCLUDES));
MutablePropertySources propertySources = environment.getPropertySources();
Properties prop = new Properties();
prop.put(SPRING_EXCLUDE_KEY, String.join(",", targetExcludes));
propertySources.addFirst(new PropertiesPropertySource("customExcludeProperties", prop));
}
}在
META-INF/spring.factories
文件中进行配置org.springframework.boot.env.EnvironmentPostProcessor=com.xxx.xxx.ExcludeEnvironmentPostProcessor
评论