1. 程式人生 > >獲取ApplicationContext進而獲取Ioc例項方法

獲取ApplicationContext進而獲取Ioc例項方法

在正常情況下 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);

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