将DTO从Spring Boot Interceptor传递给Controller

时间:2018-01-15 13:42:55

标签: java spring spring-boot dependency-injection spring-filter

我想将一个DTO从Interceptor传递给Controller?我该怎么办? 我试过定义

a)创建一个组件(需要转移) b)在Interceptor中,通过自动连线获取实例,将数据设置为自动连线实例 c)在控制器中获取自动连接的实例,但这似乎不起作用。

我总是在Controller中获取空白对象?

组件

@RequestScope
@Component
public class UserLoginInfoDTO {

    private int userId;
    private String email;
    private String firstName;
    private String lastName;

    .. setters / getters


}

HandleInterceptor

@Component
public class Inter implements HandlerInterceptor {

    @Autowired
    private UserLoginInfoDTO user;

    @Override
    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception {
        // TODO Auto-generated method stub
        System.out.println("After completion");
    }

    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
            throws Exception {
        // TODO Auto-generated method stub
        System.out.println("Post Handle");

    }

    @Override
    public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {
        // TODO Auto-generated method stub
        System.out.println("Pre Handle");
        user.setEmail("anki.vv");
        return true;
    }

}

在Controller中,如果我获得自动装配的实例并打印它,则返回空白对象。

我已经被Handle Interceptor注册为

@Override
    public void addInterceptors(InterceptorRegistry arg0) {

           ApplicationContext ctx = new AnnotationConfigApplicationContext(Demo.class);
            Inter helloWorld = ctx.getBean(Inter.class);

        arg0.addInterceptor(helloWorld);
        // TODO Auto-generated method stub

    }

演示是配置类

@Configuration
public class Demo {

    @Bean
    public Inter inter() {
        return new Inter();
    }

    @Bean
    public UserLoginInfoDTO uu() {
        return new UserLoginInfoDTO();
    }
}

1 个答案:

答案 0 :(得分:0)

我建议将共享DTO封装到@RequestScrope bean中。在我看来,这是分享请求特定数据的最简洁方法。