admin管理员组

文章数量:1530036

背景介绍

最近做的一个项目,其一需要用到Spring 的oauth认证功能, 其二需要对spring 的ContextRefreshedEvent 这个事件进行监听,实现一部分自定义注解的功能(具体功能不作赘述),本来以为毫不相关的两个功能,却出现了一些意料之外的异常。下面是一些具体的异常排查过程以及最终的解决方案,若有部分理解错误或描述错误,欢迎指正(自创文章,如需转载请说明出处)。


场景

  1. 引入Spring Security Oauth2,通过 @EnableOAuthClient 注解激活所需oauth认证功能
  2. 监听ContextRefreshedEvent事件,从ApplicationContext中获取所有的bean names并根据相应的bean name获取到bean,具体代码如下:
/**
 * @author Lanny Yao
 * @date 8/30/2018 9:58 AM
 */
@Component
public class Listener implements ApplicationListener<ContextRefreshedEvent> {
   

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        ApplicationContext context = event.getApplicationContext();
        String[] beanNames = context.getBeanNamesForType(Object.class);

        for (String beanName : beanNames){
            Object bean = context.getBean(beanName);
            ...
        }
    }
}

启动程序,抛出异常

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'scopedTarget.oauth2ClientContext': Scope 'session' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton; nested exception is java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:362) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1089) ~[spring-context-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at com.lanny.blog.demo.seesionexception.Listener.onApplicationEvent(Listener.java:21) ~[classes/:na]
    at com.lanny.blog.demo.seesionexception.Listener.onApplicationEvent(Listener.java:12) ~[classes/:na]
    at org.springframework.context.event.SimpleApplicationEventMulticaster.doInvokeListener(SimpleApplicationEventMulticaster.java:172) ~[spring-context-5.0.8.

本文标签: 过程中异常解决方案bootSpring