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

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM