JAVA SE系列

1. 判断一个字符串是否是一个有效的罗马数字

1
2
// 正则
private static final Pattern ROMAN = Pattern.compile("^(?=.)M*(C[MD]|D?C{0,3})(X[CL]|L?X{0,3})(I[XV]|V?I{0,3})$");

2. 判断一个数是否是2的整数次幂

1
2
3
private static boolean isPowerOfTwo(int val) {
return (val & -val) == 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
    34
    public 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"};

    @Override
    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

    image-20241218164910621