huangxz
2026-02-16 30432ca64a76c9273907bfab432d66611f18c1d6
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package com.xiaopeng.automaticPilot.config;
 
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.Ordered;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
 
import java.util.Map;
import java.util.Properties;
 
/**
 * 修复 ShardingSphere 5.0.0 + Spring Boot 2.x 启动时 algorithm-expression 为 null 的问题。
 */
@Component
public class ShardingAlgorithmPropsFixer implements BeanFactoryPostProcessor, EnvironmentAware, Ordered {
 
    private static final String ALGO_PREFIX = "spring.shardingsphere.rules.sharding.sharding-algorithms";
    private Environment environment;
 
    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }
 
    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE;
    }
 
    @Override
    @SuppressWarnings("unchecked")
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        Map<String, Object> algorithms;
        try {
            algorithms = Binder.get(environment)
                    .bind(ALGO_PREFIX, Map.class)
                    .orElse(null);
        } catch (Exception e) {
            return;
        }
        if (algorithms == null) {
            return;
        }
 
        for (Map.Entry<String, Object> entry : algorithms.entrySet()) {
            String algoName = entry.getKey();
            Object value = entry.getValue();
            if (!(value instanceof Map)) continue;
            if (!beanFactory.containsBeanDefinition(algoName)) continue;
 
            Map<String, Object> algoConfig = (Map<String, Object>) value;
            Object propsObj = algoConfig.get("props");
            if (!(propsObj instanceof Map)) continue;
 
            Map<String, Object> propsMap = (Map<String, Object>) propsObj;
            Properties props = new Properties();
            for (Map.Entry<String, Object> pe : propsMap.entrySet()) {
                if (pe.getValue() != null) {
                    props.put(pe.getKey(), pe.getValue().toString());
                }
            }
 
            BeanDefinition bd = beanFactory.getBeanDefinition(algoName);
            bd.getPropertyValues().addPropertyValue("props", props);
        }
    }
}