Java 使用HandlerInterceptorAdapter在SpringRestController中为每个请求注入对象

Java 使用HandlerInterceptorAdapter在SpringRestController中为每个请求注入对象,java,spring,spring-boot,autowired,spring-restcontroller,Java,Spring,Spring Boot,Autowired,Spring Restcontroller,我目前有一个使用Spring的RestController的RESTWeb服务。我实现了一个HandlerInterceptorAdapter,我想在其中设置一些用户数据 代码如下: @Component public class UserContextInterceptor extends HandlerInterceptorAdapter { @Autowired private UserContext userContext; @Override public bool

我目前有一个使用Spring的RestController的RESTWeb服务。我实现了一个HandlerInterceptorAdapter,我想在其中设置一些用户数据

代码如下:

@Component
public class UserContextInterceptor extends HandlerInterceptorAdapter {

  @Autowired
  private UserContext userContext;

  @Override
  public boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    //set userContext here
    userContext.setLoginId("loginId");

    return true;
  }
}
以下是RestController:

@RestController
public class MyController {

  @Autowired
  private MyService myService;

  @GetMapping
  public Response processRequest(Request request) {
    return myService.processRequest(request);
  }
}
@Service
public class MyService {

  @Autowired
  private UserContext userContext;

  public Response processRequest(Request request) {
    //process request using userContext
    if (userContext.getLoginId() == null)
      throw new InvalidloginException("No login id!");
    //do something else
    return new Response();
  }
}
这是服务。这只是由控制器调用:

@RestController
public class MyController {

  @Autowired
  private MyService myService;

  @GetMapping
  public Response processRequest(Request request) {
    return myService.processRequest(request);
  }
}
@Service
public class MyService {

  @Autowired
  private UserContext userContext;

  public Response processRequest(Request request) {
    //process request using userContext
    if (userContext.getLoginId() == null)
      throw new InvalidloginException("No login id!");
    //do something else
    return new Response();
  }
}
UserContext只是一个包含用户特定字段的POJO

在我的实现中,我认为UserContext不是线程安全的。每次请求到来时,都会覆盖UserContext对象。 我想知道如何正确地自动连接/注释它,以便每次收到请求时都需要一个新的UserContext。用户上下文将被正确地注入MyService。 这意味着MyService.processRequest中的所有调用都将始终注入不同的UserContext

我想到的一个解决方案就是在MyService.processRequest()方法中传递UserContext对象。我只是想知道是否可以使用Spring的autowire或其他注释来解决这个问题

有什么想法吗


谢谢

您可能希望使用请求范围的bean,而不是@KishoreKirdat中描述的单例bean。请求作用域bean解决我的问题。我用这个来解决这个问题