1. 程式人生 > >Spring Boot(5)---常用註解總結

Spring Boot(5)---常用註解總結

Spring Boot常用註解總結

@RestController和@RequestMapping註解

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

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

1 @Target(value=TYPE)    
2  @Retention(value=RUNTIME)    
3  @Documented    
4  @Controller    
5  @ResponseBody    
6 public @interface RestController 

注: @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 註解的排除屬性來禁用它們。

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

 1 @ComponentScan(basePackages = "com.hyxt",includeFilters = {@ComponentScan.Filter(Aspect.class)}) 

@SpringBootApplication

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

複製程式碼

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約束註解:

複製程式碼

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標記,從而限制載入它的時機。

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: 用在方法的引數前面。

 1 @RequestParam String a =request.getParameter("a")  @PathVariable: 路徑變數。

1     RequestMapping("user/get/mac/{macAddress}")  
2     public String getByMacAddress(@PathVariable String macAddress){  
3     //do something;  
4     }  

引數與大括號裡的名字一樣要相同。

以上註解的示範

複製程式碼

 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 } 

複製程式碼

 1 @RequestMapping("/list/{applyId}") 2 public String list(@PathVariable Long applyId, HttpServletRequest request, ModelMap modelMap) {  } 

全域性處理異常的:

@ControllerAdvice:

包含@Component。可以被掃描到。 統一處理異常。 @ExceptionHandler(Exception.class): 用在方法上面表示遇到這個異常就執行以下方法。

複製程式碼

 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裡面的配置

1     # face++ key  
2     face_api_key = R9Z3Vxc7ZcxfewgVrjOyrvu1d-qR****  
3     face_api_secret =D9WUQGCYLvOCIdsbX35uTH********  
1     @Value("${face_api_key}")  
2        private String API_KEY;  
3       
4        @Value("${face_api_secret}")  
5        private String API_SECRET;  

注意使用這個註解的時候 使用@Value的類如果被其他類作為物件引用,必須要使用注入的方式,而不能new。

所以一般常用的配置都是配置在application.properties檔案中的。