import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
* 获取到当前IOC的容器对象
*/
@Component
public class MyAppContext implements ApplicationContextAware {
private static ApplicationContext context = null;
/**
* Spring在初始化IOC时,会调用实现了ApplicationContextAware接口的类,将他的容器对象传给实现方法
*
* @param context IOC创建的容器
*/
public void setApplicationContext(ApplicationContext context) {
MyAppContext.setContext(context);
}
/**
* 取得存储在静态变量中的ApplicationContext.
*/
public static ApplicationContext getContext() {
if (context == null) {
throw new IllegalStateException("applicaitonContext未注入,请在applicationContext.xml中定义AppContext");
}
return context;
}
/**
* 存储静态变量中的ApplicationContext.
*/
public static void setContext(ApplicationContext context) {
MyAppContext.context = context;
}
/**
* 从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型
*/
public static <T> 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<String, Animal> getAll() {
Map<String, Animal> animalMap = MyAppContext.getContext().getBeansOfType(Animal.class);
return animalMap;
}
}