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);
    }

  

posted @ 2020-08-05 17:05  曾饺  阅读(421)  评论(0编辑  收藏  举报