springboot获取IOC(ApplicationContext)实例

在正常情况下 spring管理的类可直接调用Ioc容器中的实例,但在一些特殊情况下(例如拦截器中获取dao实例),Bean需要实现某个功能,但该功能必须借助于Spring容器才能实现,此时就必须让该Bean先获取Spring容器,

spring提供了ApplicationContextAware接口,容器会自动检索实现该接口的类进行spring上下文注入

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class SpringUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (SpringUtil.applicationContext == null) {
            SpringUtil.applicationContext = applicationContext;
        }
        log.info("ApplicationContext config success");
    }

    // 获取applicationContext
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    // 通过name获取 Bean.
    public static Object getBean(String name) {
        return getApplicationContext().getBean(name);
    }

    // 通过class获取Bean.
    public static <T> T getBean(Class<T> clazz) {
        return getApplicationContext().getBean(clazz);
    }

    // 通过name,以及Clazz返回指定的Bean
    public static <T> T getBean(String name, Class<T> clazz) {
        return getApplicationContext().getBean(name, clazz);
    }

}

使用例子,拦截器中获取 redis缓存实例

public class AccessInterceptor implements HandlerInterceptor {

    private IStringCacheService cache = SpringUtil.getBean(IStringCacheService.class);

    ......
    ......
    ......
    ......
    ......  
}

 

posted @ 2019-01-08 10:50  zincredible  阅读(2989)  评论(0编辑  收藏  举报