@RestController和@RequestMapping注解
4.0重要的一個(gè)新的改進(jìn)是@RestController注解,它繼承自@Controller注解。4.0之前的版本,Spring MVC的組件都使用@Controller來標(biāo)識(shí)當(dāng)前類是一個(gè)控制器servlet。使用這個(gè)特性,我們可以開發(fā)REST服務(wù)的時(shí)候不需要使用@Controller而專門的@RestController。
當(dāng)你實(shí)現(xiàn)一個(gè)RESTful web services的時(shí)候,response將一直通過response body發(fā)送。為了簡(jiǎn)化開發(fā),Spring 4.0提供了一個(gè)專門版本的controller。下面我們來看看@RestController實(shí)現(xiàn)的定義:
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請(qǐng)求都應(yīng)該被映射到 home 方法。 @RestController 注解告訴Spring以字符串的形式渲染結(jié)果,并直接返回給調(diào)用者。
注: @RestController 和 @RequestMapping 注解是Spring MVC注解(它們不是Spring Boot的特定部分)
@EnableAutoConfiguration注解
第二個(gè)類級(jí)別的注解是 @EnableAutoConfiguration 。這個(gè)注解告訴Spring Boot根據(jù)添加的jar依賴猜測(cè)你想如何配置Spring。由于 spring-boot-starter-web 添加了Tomcat和Spring MVC,所以auto-configuration將假定你正在開發(fā)一個(gè)web應(yīng)用并相應(yīng)地對(duì)Spring進(jìn)行設(shè)置。Starter POMs和Auto-Configuration:設(shè)計(jì)auto-configuration的目的是更好的使用"Starter POMs",但這兩個(gè)概念沒有直接的聯(lián)系。你可以自由地挑選starter POMs以外的jar依賴,并且Spring Boot將仍舊盡最大努力去自動(dòng)配置你的應(yīng)用。
你可以通過將 @EnableAutoConfiguration 或 @SpringBootApplication 注解添加到一個(gè) @Configuration 類上來選擇自動(dòng)配置。
注:你只需要添加一個(gè) @EnableAutoConfiguration 注解。我們建議你將它添加到主 @Configuration 類上。
如果發(fā)現(xiàn)應(yīng)用了你不想要的特定自動(dòng)配置類,你可以使用 @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的配置。盡管你可以使用一個(gè)XML源來調(diào)用 SpringApplication.run() ,我們通常建議你使用 @Configuration 類作為主要源。一般定義 main 方法的類也是主要 @Configuration 的一個(gè)很好候選。你不需要將所有的 @Configuration 放進(jìn)一個(gè)單獨(dú)的類。 @Import 注解可以用來導(dǎo)入其他配置類。另外,你也可以使用 @ComponentScan 注解自動(dòng)收集所有的Spring組件,包括 @Configuration 類。
如果你絕對(duì)需要使用基于XML的配置,我們建議你仍舊從一個(gè) @Configuration 類開始。你可以使用附加的 @ImportResource 注解加載XML配置文件。
@Configuration注解該類,等價(jià) 與XML中配置beans;用@Bean標(biāo)注方法等價(jià)于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開發(fā)者總是使用 @Configuration , @EnableAutoConfiguration 和 @ComponentScan 注解他們的main類。由于這些注解被如此頻繁地一塊使用(特別是你遵循以上最佳實(shí)踐時(shí)),Spring Boot提供一個(gè)方便的 @SpringBootApplication 選擇。
該 @SpringBootApplication 注解等價(jià)于以默認(rèn)屬性使用 @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將嘗試校驗(yàn)外部的配置,默認(rèn)使用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提供了一種隔離應(yīng)用程序配置的方式,并讓這些配置只能在特定的環(huán)境下生效。任何 @Component 或 @Configuration 都能被 @Profile 標(biāo)記,從而限制加載它的時(shí)機(jī)。 [java] view plain copy print?在CODE上查看代碼片派生到我的代碼片 @Configuration @Profile ( "production" ) public class ProductionConfiguration { // ... } @Configuration @Profile ( "production" ) public class ProductionConfiguration { // ... } @ResponseBody |
表示該方法的返回結(jié)果直接寫入HTTP response body中
一般在異步獲取數(shù)據(jù)時(shí)使用,在使用@RequestMapping后,返回值通常解析為跳轉(zhuǎn)路徑,加上
@responsebody后返回結(jié)果不會(huì)被解析為跳轉(zhuǎn)路徑,而是直接寫入HTTP response body中。比如
異步獲取json數(shù)據(jù),加上@responsebody后,會(huì)直接返回json數(shù)據(jù)。
@Component:
泛指組件,當(dāng)組件不好歸類的時(shí)候,我們可以使用這個(gè)注解進(jìn)行標(biāo)注。一般公共的方法我會(huì)用上這個(gè)注解
@AutoWired
byType方式。把配置好的Bean拿來用,完成屬性、方法的組裝,它可以對(duì)類成員變量、方法及構(gòu)
造函數(shù)進(jìn)行標(biāo)注,完成自動(dòng)裝配的工作。
當(dāng)加上(required=false)時(shí),就算找不到bean也不報(bào)錯(cuò)。
@RequestParam:
用在方法的參數(shù)前面。
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; } |
參數(shù)與大括號(hào)里的名字一樣要相同。
以上注解的示范
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
|
/** * 用戶進(jìn)行評(píng)論及對(duì)評(píng)論進(jìn)行管理的 Controller 類; */ @Controller @RequestMapping ( "/msgCenter" ) public class MyCommentController extends BaseController { @Autowired CommentService commentService; @Autowired OperatorService operatorService; /** * 添加活動(dòng)評(píng)論; * * @param applyId 活動(dòng) ID; * @param content 評(píng)論內(nèi)容; * @return */ @ResponseBody @RequestMapping ( "/addComment" ) public Map<String, Object> addComment( @RequestParam ( "applyId" ) Integer applyId, @RequestParam ( "content" ) String content) { .... return result; } } /** * 用戶進(jìn)行評(píng)論及對(duì)評(píng)論進(jìn)行管理的 Controller 類; */ @Controller @RequestMapping ( "/msgCenter" ) public class MyCommentController extends BaseController { @Autowired CommentService commentService; @Autowired OperatorService operatorService; /** * 添加活動(dòng)評(píng)論; * * @param applyId 活動(dòng) ID; * @param content 評(píng)論內(nèi)容; * @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。可以被掃描到。
統(tǒng)一處理異常。
@ExceptionHandler(Exception.class):
用在方法上面表示遇到這個(gè)異常就執(zhí)行以下方法。
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" , "參數(shù)類型錯(cuò)誤" ); 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" , "參數(shù)類型錯(cuò)誤" ); 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 的常用注解使用小結(jié),希望對(duì)大家有所幫助,如果大家有任何疑問歡迎給我留言,小編會(huì)及時(shí)回復(fù)大家的!