Spring上下文注入
首先明确一点,Spring上下文是为了解决无法自动注入而扩展使用的。
相关代码如下:
public class SpringContextUtils implements ApplicationContextAware {
/**
* spring应用上下文环境
*/
private static ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
context = applicationContext;
}
public static ApplicationContext getContext() {
return context;
}
/**
* 获取spring上下文中的bean
*
* @param <T>
* 注册bean的类型
* @param beanName
* 注册bean的名称
* @return
*/
@SuppressWarnings("unchecked")
public static <T> T getBean(String beanName) {
return (T) context.getBean(beanName);
}
/**
* 获取spring上下文中的bean
*
* @param <T>
* 注册bean的类型
* @param beanName
* 注册bean的名称
* @return
*/
@SuppressWarnings("unchecked")
public static <T> T getBean(Class<?> clazz) {
return (T) context.getBean(clazz);
}

浙公网安备 33010602011771号