
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class MyAppContext implements ApplicationContextAware {
private static ApplicationContext context = null;
public void setApplicationContext(ApplicationContext context) {
MyAppContext.setContext(context);
}
public static ApplicationContext getContext() {
if (context == null) {
throw new IllegalStateException("applicaitonContext未注入,请在applicationContext.xml中定义AppContext");
}
return context;
}
public static void setContext(ApplicationContext context) {
MyAppContext.context = context;
}
public static T getBean(String name) {
if (context == null)
throw new IllegalStateException("applicaitonContext未注入,请在applicationContext.xml中定义AppContext");
try {
return (T) context.getBean(name);
} catch (BeansException e) {
e.printStackTrace();
}
return (T) null;
}
}
Animal为一个接口类,animalMap中获取到IOC容器中实现了Animal接口的所有类对象;所有的实现了必须机上@Component注解,交给IOC管理
@Component
public class Test {
public Map getAll() {
Map animalMap = MyAppContext.getContext().getBeansOfType(Animal.class);
return animalMap;
}
}
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)