1 工厂类
public class TestFactory {
/**
*
*/
private static Map<String, TestInterface> beanMap = ContextUtil.getContext().getBeansOfType(TestInterface.class, false, false);
public static TestInterface getInstance(String infType) {
TestInterface curInstance = null;
for (String beanName : beanMap.keySet()) {
TestInterface instance = beanMap.get(beanName);
if (instance.getType() == null)
throw new RuntimeException("接口实现类类型不可以为空");
else {
if (infType.equals(instance.getType())) {
curInstance = instance;
break;
}
}
}
return curInstance;
}
}
2 获取bean类
根据Spring
上下文得到某个接口的实现类。
public class ContextUtil implements ApplicationContextAware {
private static ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
ContextUtil.context = applicationContext;
}
public static ApplicationContext getContext() {
return context;
}
}
3 需要获取实例的接口类
public interface TestInterface<T> {
String getType();
void testFunc(T t);
}
4 TestInterface
的一个实现类
public class TestInterfaceImpl implements TestInterface<String> {
@Override
public String getType() {
return "1";
}
@Override
public void testFunc(String s) {
System.out.println("TestInterfaceImpl -- 01");
}
}
原文地址:https://www.cnblogs.com/imisty/p/11227983.html
时间: 2024-11-01 19:58:39