如何使用带有Spring的java配置在拦截器中注入会话范围bean

时间:2014-01-28 11:15:44

标签: java spring session spring-mvc interceptor

我正在开发一个完整的Spring 3.1和servlet 3.0应用程序。但我的拦截器有一个私有属性作为代理:

public class MyInterceptor extends HandlerInterceptorAdapter {

    @Ressource
    private UserSession userSession;
}

用户会话定义为:

@Component 
@Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS) 
public class UserSession implements Serializable {
   ....
}

在拦截器中使用此用户会话时,java会为NullPointerException抛出userSession

我认为问题来自于我的面向javaconfig的弹簧配置:

@EnableWebMvc
@ComponentScan(basePackages = {"com.whatever"})
@Configuration
public class WebAppConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new MyInterceptor());
    }

    ...
}

问题是拦截器是手动即时的,所以没有会话代理机制的工具。因此,问题是:“我怎样才能让Spring在我的应用程序的java配置中检测并实例化范围会话代理bean?

2 个答案:

答案 0 :(得分:6)

您发布的内容有效,但您没有利用Spring的自动装配功能。如果您有许多服务或其他bean注入您的MyInterceptor bean,该怎么办?

而只是为@Bean

制作MyInterceptor方法
@EnableWebMvc
@ComponentScan(basePackages = {"com.whatever"})
@Configuration
public class WebAppConfig extends WebMvcConfigurerAdapter {

    @Bean
    @Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
    public UserSession userSession() {
        return new UserSession();
    }

    @Bean
    public MyInterceptor myInterceptor() {
        return new MyInterceptor(); // let Spring go nuts injecting stuff
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(myInterceptor()); // will always refer to the same object returned once by myInterceptor()
    }

    ...
}

答案 1 :(得分:0)

解决方案是在java配置类中使用注释:

@EnableWebMvc
@ComponentScan(basePackages = {"com.whatever"})
@Configuration
public class WebAppConfig extends WebMvcConfigurerAdapter {

    @Bean
    @Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
    public UserSession userSession() {
        return new UserSession();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        MyInterceptor interceptor = new MyInterceptor();
        interceptor.setUserSession(userSession());
        registry.addInterceptor(interceptor);
    }

    ...
}

您需要从@Scope课程中删除@BeanUserSession注释。