Kar*_*och 4 java session spring 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会抛出一个NullPointerExceptionfor 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?
您发布的内容有效,但您没有利用Spring的自动装配功能.如果你有很多服务或其他bean注入你的MyInterceptorbean 会怎么样?
而只是@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()
    }
    ...
}
| 归档时间: | 
 | 
| 查看次数: | 7215 次 | 
| 最近记录: |