springboot获取IOC(ApplicationContext)实例
在正常情况下 spring管理的类可直接调⽤Ioc容器中的实例,但在⼀些特殊情况下(例如中获取dao实例),Bean需要实现某个功能,但该功能必须借助于Spring容器才能实现,此时就必须让该Bean先获取Spring容器,
spring提供了ApplicationContextAware接⼝,容器会⾃动检索实现该接⼝的类进⾏spring上下⽂注⼊
import org.springframework.beans.BeansException;
import t.ApplicationContext;
import t.ApplicationContextAware;
import org.springframework.stereotype.Component;
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 = Bean(IStringCacheService.class);
......
......
......
......
.springboot和过滤器
.....
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。