Spring使用Yaml配置的场景

在系统开发中,会有一些通用的场景进行处理,所以代码上,对通用的部分进行处理(工厂模式)
ICreator.java

public interface ICreator {
    void doProcess();
}

YmlExampleFactory.java
用于获取当前Creator

public class YmlExampleFactory implements InitializingBean {

    @Resource
    private List creators;

    private Map ymlMap;

    private Map mappingMap;

    public void setYmlMap(Map ymlMap) {
        this.ymlMap = ymlMap;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        initHandler(ymlMap);
    }

    private void initHandler(Map ymlMap) {
        Map iCreatorMap = new HashMap<>();
        for (ICreator creator : creators) {
            iCreatorMap.put(creator.getClass().getName(), creator);
        }
        mappingMap = new HashMap<>();
        ymlMap.forEach((key, value) -> {
            if (key.startsWith("[") && key.endsWith("]")) {
                key = key.substring(1, key.length() - 1);
                for (String creatorName : Splitter.on("|").splitToList(key)) {
                    ICreator iCreator = iCreatorMap.get(creatorName);
                    if (Objects.isNull(iCreator)) {
                        throw new RuntimeException("no creator mapping");
                    }
                    Object[] objs = new Object[]{iCreator};
                    mappingMap.put(creatorName, objs);
                }
            }
        });
    }

    public ICreator getCreator(String creatorId) {
        Object[] objs = mappingMap.get(creatorId);
        if (Objects.nonNull(objs) && objs.length > 0) {
            return (ICreator) objs[0];
        }
        throw new RuntimeException("no creator mapping");
    }
}

SpringContextUtil.java

public class SpringContextUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext;
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    public static  T getBean(Class clazz){
        return applicationContext.getBean(clazz);
    }

    public static  T getBean(String beanName,Class clazz){
        return applicationContext.getBean(beanName,clazz);
    }
}
 
        
            
                
                    
                        classpath:xxx.yml
                    
                
            
        
    

xxx.yml

1: xxx.xxx.Creator

CreatorRun.java

public class CreatorRun {
    YmlExampleFactory exampleFactory = SpringContextUtil.getBean(YmlExampleFactory.class);
    public void execute(){
        String creatorId = "";
        ICreator creator = exampleFactory.getCreator(creatorId);
        creator.doProcess();
    }
}

你可能感兴趣的:(Spring使用Yaml配置的场景)