我有一个带有Spring 5的Api端点作为@RestController,我想一次为所有端点指定Cache-Control(通过Config或Annotation,......)。
目前我对每种方法都这样做。我还必须使用ResponseEntity来设置Cache-Control,这会使代码更加膨胀。
@RestController
@RequestMapping("/api")
public class MyApi {
@PostMapping("/search")
public ResponseEntity<SearchResultDto> search(SearchDto searchDto) {
// ...
return ResponseEntity.ok()
.cacheControl(CacheControl.maxAge(20, TimeUnit.SECONDS))
.body(searchResultDto);
}
@GetMapping("/get")
public ResponseEntity<EntityDto> get(Long id) {
// ...
return ResponseEntity.ok()
.cacheControl(CacheControl.maxAge(20, TimeUnit.SECONDS))
.body(entityDto);
}
// ... more methods
}
@Aspect
@Component
public class CacheAspect {
@Pointcut("within(io.company.MyApi)")
public void apiMethods() {
}
@Around("apiMethods()")
public Object addCacheControlOnResponseEntity(ProceedingJoinPoint pjp) throws Throwable {
Object retval = pjp.proceed();
if (retval instanceof ResponseEntity) {
((ResponseEntity) retval).getHeaders().setCacheControl(CacheControl.maxAge(15, TimeUnit.SECONDS));
// exception is thrown, because map can not be modified anymore
}
return retval;
}
}
@EnableWebMvc
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new HandlerInterceptor() {
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
response.setHeader(HttpHeaders.CACHE_CONTROL, CacheControl.maxAge(2, TimeUnit.SECONDS).getHeaderValue());
// header does not get modified
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
response.setHeader(HttpHeaders.CACHE_CONTROL, CacheControl.maxAge(2, TimeUnit.SECONDS).getHeaderValue());
// header does not get modified
}
});
}
}
@EnableWebMvc
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
registry.addResourceHandler("/api/**")
.setCacheControl(CacheControl.maxAge(10, TimeUnit.SECONDS));
// didn't had any effect
}
}
......我没有想法
如何减少重复/样板代码?