How to inject bean session scope into interceptor using java config using Spring

I am developing a complete Spring 3.1 application and servlet 3.0. But my interceptor has private properties limited as a proxy:

public class MyInterceptor extends HandlerInterceptorAdapter {

    @Ressource
    private UserSession userSession;
}

A user session is defined as:

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

When using this user session in an interceptor, java throws NullPointerExceptionfor userSession.

I think the problem is with my javaconfig-oriented Spring configuration:

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

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

    ...
}

The problem is that the interceptor is started manually, therefore, without tools for the session proxy mechanism. Thus, the question arises: "How can I let Spring detect and indicate the bean of the bean visibility session in the java config of my application?

+4
2

, , , autwiring Spring. , beans 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()
    }

    ...
}
+6

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 @Bean UserSession.

0

Source: https://habr.com/ru/post/1524055/


All Articles