spring boot 的常用注解使用小結(jié)
@RestController和@RequestMapping注解
4.0重要的一個(gè)新的改進(jìn)是@RestController注解,它繼承自@Controller注解。4.0之前的版本,Spring MVC的組件都使用@Controller來(lái)標(biāo)識(shí)當(dāng)前類是一個(gè)控制器servlet。使用這個(gè)特性,我們可以開(kāi)發(fā)REST服務(wù)的時(shí)候不需要使用@Controller而專門的@RestController。
當(dāng)你實(shí)現(xiàn)一個(gè)RESTful web services的時(shí)候,response將一直通過(guò)response body發(fā)送。為了簡(jiǎn)化開(kāi)發(fā),Spring 4.0提供了一個(gè)專門版本的controller。下面我們來(lái)看看@RestController實(shí)現(xiàn)的定義:
@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任何來(lái)自"/"路徑的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將假定你正在開(kāi)發(fā)一個(gè)web應(yīng)用并相應(yīng)地對(duì)Spring進(jìn)行設(shè)置。Starter POMs和Auto-Configuration:設(shè)計(jì)auto-configuration的目的是更好的使用"Starter POMs",但這兩個(gè)概念沒(méi)有直接的聯(lián)系。你可以自由地挑選starter POMs以外的jar依賴,并且Spring Boot將仍舊盡最大努力去自動(dòng)配置你的應(yīng)用。
你可以通過(guò)將 @EnableAutoConfiguration 或 @SpringBootApplication 注解添加到一個(gè) @Configuration 類上來(lái)選擇自動(dòng)配置。
注:你只需要添加一個(gè) @EnableAutoConfiguration 注解。我們建議你將它添加到主 @Configuration 類上。
如果發(fā)現(xiàn)應(yīng)用了你不想要的特定自動(dòng)配置類,你可以使用 @EnableAutoConfiguration 注解的排除屬性來(lái)禁用它們。
<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源來(lái)調(diào)用 SpringApplication.run() ,我們通常建議你使用 @Configuration 類作為主要源。一般定義 main 方法的類也是主要 @Configuration 的一個(gè)很好候選。你不需要將所有的 @Configuration 放進(jìn)一個(gè)單獨(dú)的類。 @Import 注解可以用來(lái)導(dǎo)入其他配置類。另外,你也可以使用 @ComponentScan 注解自動(dòng)收集所有的Spring組件,包括 @Configuration 類。
如果你絕對(duì)需要使用基于XML的配置,我們建議你仍舊從一個(gè) @Configuration 類開(kāi)始。你可以使用附加的 @ImportResource 注解加載XML配置文件。
@Configuration注解該類,等價(jià) 與XML中配置beans;用@Bean標(biāo)注方法等價(jià)于XML中配置bean
@ComponentScan(basePackages = "com.hyxt",includeFilters = {@ComponentScan.Filter(Aspect.class)}) @ComponentScan(basePackages = "com.hyxt",includeFilters = {@ComponentScan.Filter(Aspect.class)}) @SpringBootApplication
很多Spring Boot開(kāi)發(fā)者總是使用 @Configuration , @EnableAutoConfiguration 和 @ComponentScan 注解他們的main類。由于這些注解被如此頻繁地一塊使用(特別是你遵循以上最佳實(shí)踐時(shí)),Spring Boot提供一個(gè)方便的 @SpringBootApplication 選擇。
該 @SpringBootApplication 注解等價(jià)于以默認(rèn)屬性使用 @Configuration , @EnableAutoConfiguration 和 @ComponentScan 。
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約束注解:
@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拿來(lái)用,完成屬性、方法的組裝,它可以對(duì)類成員變量、方法及構(gòu)
造函數(shù)進(jìn)行標(biāo)注,完成自動(dòng)裝配的工作。
當(dāng)加上(required=false)時(shí),就算找不到bean也不報(bào)錯(cuò)。
@RequestParam:
用在方法的參數(shù)前面。
@RequestParam String a =request.getParameter("a")。 @RequestParam String a =request.getParameter("a")。
@PathVariable:
路徑變量。
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)里的名字一樣要相同。
以上注解的示范
/** * 用戶進(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??梢员粧呙璧健?/p>
統(tǒng)一處理異常。
@ExceptionHandler(Exception.class):
用在方法上面表示遇到這個(gè)異常就執(zhí)行以下方法。
/** * 全局異常處理 */ @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; }}
通過(guò)@value注解來(lái)讀取application.properties里面的配置
# 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ì)大家有所幫助,如果大家有任何疑問(wèn)歡迎給我留言,小編會(huì)及時(shí)回復(fù)大家的!
相關(guān)文章
RabbitMQ中的死信隊(duì)列(Dead Letter Exchanges)詳解
這篇文章主要介紹了RabbitMQ中的死信隊(duì)列(Dead Letter Exchanges)詳解,當(dāng)RabbitMQ出現(xiàn)死信,可能會(huì)導(dǎo)致業(yè)務(wù)邏輯錯(cuò)誤,比如下訂單后修改庫(kù)存操作,在下單后因?yàn)槟撤N原因,發(fā)送的消息未被簽收,這時(shí)庫(kù)存數(shù)據(jù)會(huì)出現(xiàn)不一致,需要的朋友可以參考下2023-12-12Java利用Socket類實(shí)現(xiàn)TCP通信程序
TCP通信能實(shí)現(xiàn)兩臺(tái)計(jì)算機(jī)之間的數(shù)據(jù)交互,通信的兩端,要嚴(yán)格區(qū)分為客戶端與服務(wù)端,下面我們就來(lái)看看Java如何利用Socket類實(shí)現(xiàn)TCP通信程序吧2024-02-02Java數(shù)據(jù)結(jié)構(gòu)之圖的兩種搜索算法詳解
在很多情況下,我們需要遍歷圖,得到圖的一些性質(zhì)。有關(guān)圖的搜索,最經(jīng)典的算法有深度優(yōu)先搜索和廣度優(yōu)先搜索,接下來(lái)我們分別講解這兩種搜索算法,需要的可以參考一下2022-11-11SpringBoot+JWT實(shí)現(xiàn)注冊(cè)、登錄、狀態(tài)續(xù)簽流程分析
這篇文章主要介紹了SpringBoot+JWT實(shí)現(xiàn)注冊(cè)、登錄、狀態(tài)續(xù)簽【登錄保持】,本文通過(guò)示例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-06-06SpringCloud之loadbalancer負(fù)載均衡組件實(shí)戰(zhàn)詳解
LoadBalancer是Spring Cloud官方提供的負(fù)載均衡組件,可用于替代Ribbon,這篇文章主要介紹了SpringCloud之loadbalancer負(fù)載均衡組件,需要的朋友可以參考下2023-06-06