2014-04-10 55 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