@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實現的定義:
1
2
3
4
5
6
7
8
9
10
11
12
|
@Target (value=TYPE) @Retention (value=RUNTIME) @Documented @Controller @ResponseBody public @interface RestController @Target (value=TYPE) @Retention (value=RUNTIME) @Documented @Controller @ResponseBody 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 注解的排除屬性來禁用它們。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
<pre name= "code" class = "java" > import org.springframework.boot.autoconfigure.*; import org.springframework.boot.autoconfigure.jdbc.*; import org.springframework.context.annotation.*; @Configuration @EnableAutoConfiguration (exclude={DataSourceAutoConfiguration. class }) public class MyConfiguration { } <pre name= "code" class = "java" > import org.springframework.boot.autoconfigure.*; import org.springframework.boot.autoconfigure.jdbc.*; import org.springframework.context.annotation.*; @Configuration @EnableAutoConfiguration (exclude={DataSourceAutoConfiguration. class }) public class MyConfiguration { } @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
2
3
|
@ComponentScan (basePackages = "com.hyxt" ,includeFilters = { @ComponentScan .Filter(Aspect. class )}) @ComponentScan (basePackages = "com.hyxt" ,includeFilters = { @ComponentScan .Filter(Aspect. class )}) @SpringBootApplication |
很多Spring Boot開發者總是使用 @Configuration , @EnableAutoConfiguration 和 @ComponentScan 注解他們的main類。由于這些注解被如此頻繁地一塊使用(特別是你遵循以上最佳實踐時),Spring Boot提供一個方便的 @SpringBootApplication 選擇。
該 @SpringBootApplication 注解等價于以默認屬性使用 @Configuration , @EnableAutoConfiguration 和 @ComponentScan 。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
package com.example.myproject; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication // same as @Configuration @EnableAutoConfiguration @ComponentScan public class Application { public static void main(String[] args) { SpringApplication.run(Application. class , args); } } package com.example.myproject; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication // same as @Configuration @EnableAutoConfiguration @ComponentScan public class Application { public static void main(String[] args) { SpringApplication.run(Application. class , args); } } |
Spring Boot將嘗試校驗外部的配置,默認使用JSR-303(如果在classpath路徑中)。你可以輕松的為你的@ConfigurationProperties類添加JSR-303 javax.validation約束注解:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
@Component @ConfigurationProperties (prefix= "connection" ) public class ConnectionSettings { @NotNull private InetAddress remoteAddress; // ... getters and setters } @Component @ConfigurationProperties (prefix= "connection" ) public class ConnectionSettings { @NotNull private InetAddress remoteAddress; // ... getters and setters } @Profiles Spring Profiles提供了一種隔離應用程序配置的方式,并讓這些配置只能在特定的環境下生效。任何 @Component 或 @Configuration 都能被 @Profile 標記,從而限制加載它的時機。 [java] view plain copy print?在CODE上查看代碼片派生到我的代碼片 @Configuration @Profile ( "production" ) public class ProductionConfiguration { // ... } @Configuration @Profile ( "production" ) public class ProductionConfiguration { // ... } @ResponseBody |
表示該方法的返回結果直接寫入HTTP response body中
一般在異步獲取數據時使用,在使用@RequestMapping后,返回值通常解析為跳轉路徑,加上
@responsebody后返回結果不會被解析為跳轉路徑,而是直接寫入HTTP response body中。比如
異步獲取json數據,加上@responsebody后,會直接返回json數據。
@Component:
泛指組件,當組件不好歸類的時候,我們可以使用這個注解進行標注。一般公共的方法我會用上這個注解
@AutoWired
byType方式。把配置好的Bean拿來用,完成屬性、方法的組裝,它可以對類成員變量、方法及構
造函數進行標注,完成自動裝配的工作。
當加上(required=false)時,就算找不到bean也不報錯。
@RequestParam:
用在方法的參數前面。
1
2
|
@RequestParam String a =request.getParameter( "a" )。 @RequestParam String a =request.getParameter( "a" )。 |
@PathVariable:
路徑變量。
1
2
3
4
5
6
7
8
|
RequestMapping( "user/get/mac/{macAddress}" ) public String getByMacAddress( @PathVariable String macAddress){ //do something; } RequestMapping( "user/get/mac/{macAddress}" ) public String getByMacAddress( @PathVariable String macAddress){ //do something; } |
參數與大括號里的名字一樣要相同。
以上注解的示范
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
|
/** * 用戶進行評論及對評論進行管理的 Controller 類; */ @Controller @RequestMapping ( "/msgCenter" ) public class MyCommentController extends BaseController { @Autowired CommentService commentService; @Autowired OperatorService operatorService; /** * 添加活動評論; * * @param applyId 活動 ID; * @param content 評論內容; * @return */ @ResponseBody @RequestMapping ( "/addComment" ) public Map<String, Object> addComment( @RequestParam ( "applyId" ) Integer applyId, @RequestParam ( "content" ) String content) { .... return result; } } /** * 用戶進行評論及對評論進行管理的 Controller 類; */ @Controller @RequestMapping ( "/msgCenter" ) public class MyCommentController extends BaseController { @Autowired CommentService commentService; @Autowired OperatorService operatorService; /** * 添加活動評論; * * @param applyId 活動 ID; * @param content 評論內容; * @return */ @ResponseBody @RequestMapping ( "/addComment" ) public Map<String, Object> addComment( @RequestParam ( "applyId" ) Integer applyId, @RequestParam ( "content" ) String content) { .... return result; } } @RequestMapping ( "/list/{applyId}" ) public String list( @PathVariable Long applyId, HttpServletRequest request, ModelMap modelMap) { } @RequestMapping ( "/list/{applyId}" ) public String list( @PathVariable Long applyId, HttpServletRequest request, ModelMap modelMap) { } |
全局處理異常的:
@ControllerAdvice:
包含@Component??梢员粧呙璧?。
統一處理異常。
@ExceptionHandler(Exception.class):
用在方法上面表示遇到這個異常就執行以下方法。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
/** * 全局異常處理 */ @ControllerAdvice class GlobalDefaultExceptionHandler { public static final String DEFAULT_ERROR_VIEW = "error" ; @ExceptionHandler ({TypeMismatchException. class ,NumberFormatException. class }) public ModelAndView formatErrorHandler(HttpServletRequest req, Exception e) throws Exception { ModelAndView mav = new ModelAndView(); mav.addObject( "error" , "參數類型錯誤" ); mav.addObject( "exception" , e); mav.addObject( "url" , RequestUtils.getCompleteRequestUrl(req)); mav.addObject( "timestamp" , new Date()); mav.setViewName(DEFAULT_ERROR_VIEW); return mav; }} /** * 全局異常處理 */ @ControllerAdvice class GlobalDefaultExceptionHandler { public static final String DEFAULT_ERROR_VIEW = "error" ; @ExceptionHandler ({TypeMismatchException. class ,NumberFormatException. class }) public ModelAndView formatErrorHandler(HttpServletRequest req, Exception e) throws Exception { ModelAndView mav = new ModelAndView(); mav.addObject( "error" , "參數類型錯誤" ); mav.addObject( "exception" , e); mav.addObject( "url" , RequestUtils.getCompleteRequestUrl(req)); mav.addObject( "timestamp" , new Date()); mav.setViewName(DEFAULT_ERROR_VIEW); return mav; }} |
通過@value注解來讀取application.properties里面的配置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
# face++ key face_api_key = R9Z3Vxc7ZcxfewgVrjOyrvu1d-qR**** face_api_secret =D9WUQGCYLvOCIdsbX35uTH******** # face++ key face_api_key = R9Z3Vxc7ZcxfewgVrjOyrvu1d-qR**** face_api_secret =D9WUQGCYLvOCIdsbX35uTH******** @Value ( "${face_api_key}" ) private String API_KEY; @Value ( "${face_api_secret}" ) private String API_SECRET; @Value ( "${face_api_key}" ) private String API_KEY; @Value ( "${face_api_secret}" ) private String API_SECRET;所以一般常用的配置都是配置在application.properties文件的 |
以上所述是小編給大家介紹的spring boot 的常用注解使用小結,希望對大家有所幫助,如果大家有任何疑問歡迎給我留言,小編會及時回復大家的!