在系统开发中,会有一些通用的场景进行处理,所以代码上,对通用的部分进行处理(工厂模式)
ICreator.java
public interface ICreator {
void doProcess();
}
YmlExampleFactory.java
用于获取当前Creator
public class YmlExampleFactory implements InitializingBean {
@Resource
private List<ICreator> creators;
private Map<String, String> ymlMap;
private Map<String, Object[]> mappingMap;
public void setYmlMap(Map<String, String> ymlMap) {
this.ymlMap = ymlMap;
}
@Override
public void afterPropertiesSet() throws Exception {
initHandler(ymlMap);
}
private void initHandler(Map<String, String> ymlMap) {
Map<String, ICreator> 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> T getBean(Class<T> clazz){
return applicationContext.getBean(clazz);
}
public static <T> T getBean(String beanName,Class<T> clazz){
return applicationContext.getBean(beanName,clazz);
}
}
<bean class="com.yi.mall.common.YmlExampleFactory">
<property name="ymlMap">
<bean class="org.springframework.beans.factory.config.YamlMapFactoryBean">
<property name="resources">
<list>
<value>classpath:xxx.yml</value>
</list>
</property>
</bean>
</property>
</bean>
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();
}
}