2014-04-10 57 views
0

我有一组方法具有非常类似的注释声明,如何缩短它们?不要在任何地方重复它们?如何在Java中使用typedef注释

@RequestMapping(value = "/relative_path", 
     method = RequestMethod.GET, 
     consumes = "appilcation/json", 
     produces = "appilcation/json") 
@ResponseBody 
public User method1(HttpServletRequest httpServletRequest, 
        @RequestBody String requestBody) 
{...} 

回答

1

您可以为创建弹簧元注释:

@RequestMapping(value = "/relative_path", 
    method = RequestMethod.GET, 
    consumes = "appilcation/json", 
    produces = "appilcation/json") 
@ResponseBody 
@Target(ElementType.METHOD) 
@Retention(RetentionPolicy.RUNTIME) 
public @interface MyAnnotation { 
} 

,并用它在你的方法:

@MyAnnotation 
public User method1(HttpServletRequest httpServletRequest, 
        @RequestBody String requestBody) { } 

解决方案:

@RequestMapping(method = RequestMethod.POST, 
     consumes = "appilcation/json", 
     produces = "appilcation/json") 
@Target(ElementType.METHOD) 
@Retention(RetentionPolicy.RUNTIME) 
public @interface MyAnnotation { 
} 

@RequestMapping(value = "/relative_path") 
@MyAnnotation 
public User method1(HttpServletRequest httpServletRequest, 
        @RequestBody String requestBody) { } 
+0

但如何如果“value =”/ relative_path“”更改,请执行此操作吗?谢谢 – hardbone

+0

@hardbone我想这是没有办法的。我会尽力找到。 –

+0

其实它是可行的,绝对是把两个注释放在一个方法上。往上看。非常感谢Rohit! – hardbone