ApplicationContextAware
应用:主动调用代码 getBean(“字符串”),字符串是变量,从而获取到不同的实例。可以实现类似不同参数不同bean实例的场景。
public class SpringContextUtil implements ApplicationContextAware {
private static ApplicationContext context;
@SuppressWarnings("static-access")
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
this.context = applicationContext;
}
/**
* 获取静态变量中的ApplicationContext
* @return
*/
public static ApplicationContext getContext() {
return context;
}
/**
* 根据bean name 获取对象
* @param name
* @return
*/
@SuppressWarnings("unchecked")
public static <T> T getBean(String name) {
return (T) context.getBean(name);
}
/**
* 根据Class获取对象
* @param clazz
* @param <T>
* @return
* @throws BeansException
*/
public static <T> T getBean(Class<T> clazz) throws BeansException {
return context.getBean(clazz);
}
}