常見註解


原文:http://blog.csdn.net/lafengwnagzi/article/details/53034369 

springMVC:http://blog.csdn.net/lan861698789/article/details/8051393 


@RestController和@RequestMapping註解

4.0重要的一個新的改進是@RestController註解,它繼承自@Controller註解。4.0之前的版本,spring MVC的組件都使用@Controller來標識當前類是一個控制器servlet。使用這個特性,我們可以開發REST服務的時候不需要使用@Controller而專門的@RestController。

 當你實現一個RESTful web services的時候,response將一直通過response body發送。爲了簡化開發,Spring 4.0提供了一個專門版本的controller。下面我們來看看@RestController實現的定義:

[html] view plain copy
 print?
  1. @Target(value=TYPE)    
  2.  @Retention(value=RUNTIME)    
  3.  @Documented    
  4.  @Controller    
  5.  @ResponseBody    
  6. public @interface RestController   

@RequestMapping 註解提供路由信息。它告訴Spring任何來自"/"路徑的HTTP請求都應該被映射到 home 方法。 @RestController 註解告訴Spring以字符串的形式渲染結果,並直接返回給調用者。


注: @RestController 和 @RequestMapping 註解是Spring MVC註解(它們不是Spring Boot的特定部分)

@EnableAutoConfiguration註解

第二個類級別的註解是 @EnableAutoConfiguration 。這個註解告訴Spring Boot根據添加的jar依賴猜測你想如何配置Spring。由於 spring-boot-starter-web 添加了Tomcat和Spring MVC,所以auto-configuration將假定你正在開發一個web應用並相應地對Spring進行設置。Starter POMs和Auto-Configuration:設計auto-configuration的目的是更好的使用"Starter POMs",但這兩個概念沒有直接的聯繫。你可以自由地挑選starter POMs以外的jar依賴,並且Spring Boot將仍舊盡最大努力去自動配置你的應用。

你可以通過將 @EnableAutoConfiguration 或 @SpringBootApplication 註解添加到一個 @Configuration 類上來選擇自動配置。
注:你只需要添加一個 @EnableAutoConfiguration 註解。我們建議你將它添加到主 @Configuration 類上。

如果發現應用了你不想要的特定自動配置類,你可以使用 @EnableAutoConfiguration 註解的排除屬性來禁用它們。

[html] view plain copy
 print?
  1. <pre name="code" class="java">import org.springframework.boot.autoconfigure.*;  
  2. import org.springframework.boot.autoconfigure.jdbc.*;  
  3. import org.springframework.context.annotation.*;  
  4. @Configuration  
  5. @EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})  
  6. public class MyConfiguration {  
  7. }  

@Configuration

Spring Boot提倡基於Java的配置。儘管你可以使用一個XML源來調用 SpringApplication.run() ,我們通常建議你使用 @Configuration 類作爲主要源。一般定義 main 方法的類也是主要 @Configuration 的一個很好候選。你不需要將所有的 @Configuration 放進一個單獨的類。 @Import 註解可以用來導入其他配置類。另外,你也可以使用 @ComponentScan 註解自動收集所有的Spring組件,包括 @Configuration 類。

如果你絕對需要使用基於XML的配置,我們建議你仍舊從一個 @Configuration 類開始。你可以使用附加的 @ImportResource 註解加載XML配置文件。

@Configuration註解該類,等價 與XML中配置beans;用@Bean標註方法等價於XML中配置bean

[java] view plain copy
 print?
  1. @ComponentScan(basePackages = "com.hyxt",includeFilters = {@ComponentScan.Filter(Aspect.class)})  

@SpringBootApplication

很多Spring Boot開發者總是使用 @Configuration , @EnableAutoConfiguration 和 @ComponentScan 註解他們的main類。由於這些註解被如此頻繁地一塊使用(特別是你遵循以上最佳實踐時),Spring Boot提供一個方便的 @SpringBootApplication 選擇。
該 @SpringBootApplication 註解等價於以默認屬性使用 @Configuration , @EnableAutoConfiguration 和 @ComponentScan 。

[java] view plain copy
 print?
  1. package com.example.myproject;  
  2. import org.springframework.boot.SpringApplication;  
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;  
  4. @SpringBootApplication // same as @Configuration @EnableAutoConfiguration @ComponentScan  
  5. public class Application {  
  6.     public static void main(String[] args) {  
  7.         SpringApplication.run(Application.class, args);  
  8.     }  
  9. }  

Spring Boot將嘗試校驗外部的配置,默認使用JSR-303(如果在classpath路徑中)。你可以輕鬆的爲你的@ConfigurationProperties類添加JSR-303 javax.validation約束註解:
[java] view plain copy
 print?
  1. @Component  
  2. @ConfigurationProperties(prefix="connection")  
  3. public class ConnectionSettings {  
  4. @NotNull  
  5. private InetAddress remoteAddress;  
  6. // ... getters and setters  
  7. }  

@Profiles

Spring Profiles提供了一種隔離應用程序配置的方式,並讓這些配置只能在特定的環境下生效。任何@Component或@Configuration都能被@Profile標記,從而限制加載它的時機。

[java] view plain copy
 print?
  1. @Configuration  
  2. @Profile("production")  
  3. public class ProductionConfiguration {  
  4. // ...  
  5. }  
@ResponseBody

表示該方法的返回結果直接寫入HTTP response body中

一般在異步獲取數據時使用,在使用@RequestMapping後,返回值通常解析爲跳轉路徑,加上
@responsebody後返回結果不會被解析爲跳轉路徑,而是直接寫入HTTP response body中。比如
異步獲取json數據,加上@responsebody後,會直接返回json數據。

@Component:
泛指組件,當組件不好歸類的時候,我們可以使用這個註解進行標註。一般公共的方法我會用上這個註解

@AutoWired
byType方式。把配置好的Bean拿來用,完成屬性、方法的組裝,它可以對類成員變量、方法及構
造函數進行標註,完成自動裝配的工作。
當加上(required=false)時,就算找不到bean也不報錯。

@RequestParam:
用在方法的參數前面。
[java] view plain copy
 print?
  1. @RequestParam String a =request.getParameter("a")。  

@PathVariable:
路徑變量。
[java] view plain copy
 print?
  1. RequestMapping("user/get/mac/{macAddress}")  
  2. public String getByMacAddress(@PathVariable String macAddress){  
  3. //do something;  
  4. }  
參數與大括號裏的名字一樣要相同。
以上註解的示範
[java] view plain copy
 print?
  1. /** 
  2.  * 用戶進行評論及對評論進行管理的 Controller 類; 
  3.  */  
  4. @Controller  
  5. @RequestMapping("/msgCenter")  
  6. public class MyCommentController extends BaseController {  
  7.     @Autowired  
  8.     CommentService commentService;  
  9.   
  10.     @Autowired  
  11.     OperatorService operatorService;  
  12.   
  13.     /** 
  14.      * 添加活動評論; 
  15.      * 
  16.      * @param applyId 活動 ID; 
  17.      * @param content 評論內容; 
  18.      * @return 
  19.      */  
  20.     @ResponseBody  
  21.     @RequestMapping("/addComment")  
  22.     public Map<String, Object> addComment(@RequestParam("applyId") Integer applyId, @RequestParam("content") String content) {  
  23.         ....  
  24.         return result;  
  25.     }  
  26. }  

[html] view plain copy
 print?
  1.  @RequestMapping("/list/{applyId}")  
  2.     public String list(@PathVariable Long applyId, HttpServletRequest request, ModelMap modelMap) {  
  3. }  

全局處理異常的:
@ControllerAdvice:
包含@Component。可以被掃描到。
統一處理異常。

@ExceptionHandler(Exception.class):
用在方法上面表示遇到這個異常就執行以下方法。

[java] view plain copy
 print?
  1. /** 
  2.  * 全局異常處理 
  3.  */  
  4. @ControllerAdvice  
  5. class GlobalDefaultExceptionHandler {  
  6.     public static final String DEFAULT_ERROR_VIEW = "error";  
  7.   
  8.     @ExceptionHandler({TypeMismatchException.class,NumberFormatException.class})  
  9.     public ModelAndView formatErrorHandler(HttpServletRequest req, Exception e) throws Exception {  
  10.         ModelAndView mav = new ModelAndView();  
  11.         mav.addObject("error","參數類型錯誤");  
  12.         mav.addObject("exception", e);  
  13.         mav.addObject("url", RequestUtils.getCompleteRequestUrl(req));  
  14.         mav.addObject("timestamp"new Date());  
  15.         mav.setViewName(DEFAULT_ERROR_VIEW);  
  16.         return mav;  
  17.     }}  


通過@value註解來讀取application.properties裏面的配置

[java] view plain copy
 print?
  1. # face++ key  
  2. face_api_key = R9Z3Vxc7ZcxfewgVrjOyrvu1d-qR****  
  3. face_api_secret =D9WUQGCYLvOCIdsbX35uTH********  
[java] view plain copy
 print?
  1. @Value("${face_api_key}")  
  2.    private String API_KEY;  
  3.   
  4.    @Value("${face_api_secret}")  
  5.    private String API_SECRET;  
所以一般常用的配置都是配置在application.properties文件的
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章