Spring配置文件初始化加载(一)
1.枚举
public enum TestEnum {
type_01("01", "zeroTest01ServiceImpl"),
type_02("02", "zeroTest02ServiceImpl"),
type_03("03", "zeroTest03ServiceImpl");
private String type;
private String pathClass;
}
2.接口
public interface ZeroTestService {
/**
* 校验
*
* @param map
*/
void checkData(Map<String, String> map);
/**
* 当前实现对应类型
*
* @return
*/
String getType();
}
3.实现类
@Service
public class ZeroTest02ServiceImpl implements ZeroTestService {
@Override
public void checkData(Map<String, String> map) {
}
@Override
public String getType() {
return null;
}
}
@Service
public class ZeroTest01ServiceImpl implements ZeroTestService {
@Override
public void checkData(Map<String, String> map) {
}
@Override
public String getType() {
return null;
}
}
4.实现IOC容器
@Component
public class ZeroTestServiceFactory implements ApplicationContextAware {
@Autowired
private ApplicationContext applicationContext;
public Map<String, ZeroTestService> serviceMap = new HashMap<>();
public ZeroTestService getZeroTestService(String type) {
return serviceMap.get(type);
}
@Override
public void setApplicationContext(ApplicationContext context) throws BeansException {
if (null == context) {
context = applicationContext;
}
for (TestEnum testEnum : TestEnum.values()) {
serviceMap.put(testEnum.getType(), (ZeroTestService) context.getBean(testEnum.getPathClass()));
}
}
}