我编写了一个简单的自定义批注,将 HttpHeaders 设置为 ResponseEntity ,因为在每个位置都重复了代码。
注释界面和类。
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface JsonHeader {}
@Component
@Aspect
public class JsonHeaderAspect {
private final Log logger = LogFactory.getLog(getClass());
@Around(value = "@annotation(JsonHeader)")
public Object aroundServiceResponse(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", MediaType.APPLICATION_JSON_VALUE);
return proceedingJoinPoint.proceed(new Object[] {headers});
}
}
RestController类
@RestController
@RequestMapping(path = "/login")
public class LoginRestController {
private final Log logger = LogFactory.getLog(getClass());
@Autowired
LoginServiceImpl loginService;
@JsonHeader
@RequestMapping(value = "/user",consumes = MediaType.APPLICATION_JSON_VALUE,produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<ResponseBean> postCheckUser(@RequestBody LoginBean loginBean) {
ResponseBean responseBean = loginService.checkUser(loginBean);
return new ResponseEntity<ResponseBean>(responseBean,headers, HttpStatus.OK);
}
}
现在,我想将返回的HttpHeaders值注释获取到休息控制器类。
任何人都可以描述它发生的原因以及如何解决此问题,这将对您大有帮助。预先感谢
答案 0 :(得分:0)
您可以简单地通过修改这样的建议来做到这一点。您无需在控制器中执行任何操作。
@Around(value = "@annotation(requestMapping)")
public Object aroundServiceResponse(ProceedingJoinPoint proceedingJoinPoint,RequestMapping requestMapping) throws Throwable {
String[] consumes = requestMapping.consumes();
consumes[consumes.length] = MediaType.APPLICATION_JSON_VALUE;
String[] produces = requestMapping.produces();
produces[produces.length] = MediaType.APPLICATION_JSON_VALUE;
return proceedingJoinPoint.proceed();
}