bean中拿到ApplicationContext对象

	public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof ResourceLoaderAware) {
((ResourceLoaderAware) bean).setResourceLoader(this.applicationContext);
}
if (bean instanceof ApplicationEventPublisherAware) {
((ApplicationEventPublisherAware) bean).setApplicationEventPublisher(this.applicationContext);
}
if (bean instanceof MessageSourceAware) {
((MessageSourceAware) bean).setMessageSource(this.applicationContext);
}
if (bean instanceof ApplicationContextAware) {
((ApplicationContextAware) bean).setApplicationContext(this.applicationContext);
}
return bean;
}


这个方法是定义在ApplicationContextAwareProcessor中的,一般都会注入到BeanFactory中。
从上面可以看出想要拿到ApplicationContext的方法就比较多了,看需要吧。
### 关于 `HandlerInterceptor` 和 `InterceptorRegistry` 在 Spring MVC 中,`HandlerInterceptor` 是用于拦截 HTTP 请求的接口。而 `InterceptorRegistry` 则是在配置类中用来注册多个拦截器的对象。需要注意的是,在 `HandlerInterceptor` 实现类内部无法直接调用 `InterceptorRegistry.getInterceptors()` 方法来获取所有已注册的拦截器列表。 通常情况下,`InterceptorRegistry` 只能在实现了 `WebMvcConfigurer` 接口的方法内被访问到,比如通过覆写 `addInterceptors` 方法来进行拦截器的添加操作[^2]。 如果确实有需求要在某个特定时刻获得当前应用上下文中所有的拦截器实例,则可以通过依赖注入的方式引入 `ApplicationContext` 并从中查找类型为 `HandlerInterceptor` 的 Bean 来间接达到目的: ```java @Autowired private ApplicationContext applicationContext; public List<HandlerInterceptor> getAllInterceptors() { Map<String, HandlerInterceptor> beansOfType = applicationContext.getBeansOfType(HandlerInterceptor.class); return new ArrayList<>(beansOfType.values()); } ``` 上述代码片段展示了如何利用 `ApplicationContext` 来检索所有已经作为 Spring Bean 被管理起来的 `HandlerInterceptor` 对象[^3]。 对于想要查看全局范围内有哪些拦截器生效的情况,建议还是应该回到应用程序的整体架构设计层面去考虑,而不是试图在一个具体的处理器里做这样的事情;因为这可能意味着业务逻辑与框架机制之间存在耦合度过高的风险。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值