0
@Service

    @GetMapping
    public Foo findByFooId(@RequestParam(name = "fid") String fooId) {
        return fooService.findByFooId(fooId);
    }

I would like to trigger and save who viewed Foo, using a different method in FooService. Its like a PostConstruct callback for a successful response of findByFooId. How can this be achieved

Rpj
  • 5,348
  • 16
  • 62
  • 122
  • Consider using @After from Spring AOP and do post-processing in it, this does not seem to be a use case of post-construct, since it is related to bean lifecycle https://docs.spring.io/spring-framework/docs/2.5.x/reference/aop.html – Arpit May 27 '21 at 04:59

1 Answers1

1

One way is going to a custom HandlerInterceptor implementation.

  • Definition of the interceptor
public class FooViewerInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    FooService fooService;

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
    throws Exception {
       // if response succeeded ? http response code = 200 ?
       // extract the "who" logic
       // extract the fooId from request path
       fooService.viewedBy(fooId, userId); // example...
    }

}
  • Register the interceptor. Note the path pattern specified with the custom interceptor instance.. just an example.
@Configuration  
public class AppConfig implements WebMvcConfigurer  {  

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
       registry.addInterceptor(new FooViewerInterceptor()).addPathPatterns("/foo/**");
    }
} 
CodeScale
  • 3,046
  • 1
  • 12
  • 20