Get return value in custom annotation spring aop

901 Views Asked by At

I have write a simple custom annotation to set HttpHeaders to ResponseEntity because of duplicating the code every where .

Annotation Interface and Class.

@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 Class

@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);
    }
}

Now I want to get the return HttpHeaders value annotaion to rest controller class.

Is any one can describe why it happen and how to fix this issue it will be great helpful. Thanks in advance

1

There are 1 best solutions below

1
On

You can do this simply by modifying your advice like this. You don't need to do anything in the controller.

@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();
}