Springboot 常用註解

Springboot 常用註解

@SpringBootApplication:

包含 @Configuration、@EnableAutoConfiguration、@ComponentScan
通常用在主類上。

@Repository:
用於標註數據訪問組件,即 DAO 組件。

@Service:
用於標註業務層組件。

@RestController:
用於標註控制層組件(如 struts 中的 action),包含 @Controller 和 @ResponseBody。

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

@Component:
泛指組件,當組件不好歸類的時候,我們可以使用這個註解進行標註。

@ComponentScan:
組件掃描。個人理解相當於,如果掃描到有 @Component @Controller @Service 等這些註解的類,則把這些類註冊爲 bean。

@Configuration:
指出該類是 Bean 配置的信息源,相當於 XML 中的,一般加在主類上。

@Bean:
相當於 XML 中的,放在方法的上面,而不是類,意思是產生一個 bean, 並交給 spring 管理。

@EnableAutoConfiguration:
讓 Spring Boot 根據應用所聲明的依賴來對 Spring 框架進行自動配置,一般加在主類上。

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

@Qualifier:
當有多個同一類型的 Bean 時,可以用 @Qualifier(“name”)來指定。與 @Autowired 配合使用

@Resource(name=“name”,type=“type”):
沒有括號內內容的話,默認 byName。與 @Autowired 幹類似的事。

@RequestMapping:

RequestMapping 是一個用來處理請求地址映射的註解,可用於類或方法上。用於類上,表示類中的所有響應請求的方法都是以該地址作爲父路徑。
該註解有六個屬性:
params:指定 request 中必須包含某些參數值是,才讓該方法處理。
headers:指定 request 中必須包含某些指定的 header 值,才能讓該方法處理請求。
value:指定請求的實際地址,指定的地址可以是 URI Template 模式
method:指定請求的 method 類型, GET、POST、PUT、DELETE 等
consumes:指定處理請求的提交內容類型(Content-Type),如 application/json,text/html;
produces:指定返回的內容類型,僅當 request 請求頭中的(Accept)類型中包含該指定類型才返回

@RequestParam:
用在方法的參數前面。
@RequestParam String a =request.getParameter(“a”)。

@PathVariable:

路徑變量。參數與大括號裏的名字一樣要相同。

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

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

@Configuration
@Profile(“prod”) public class ProductionConfiguration { // …
}

@ConfigurationProperties
Spring Boot 將嘗試校驗外部的配置,默認使用 JSR-303(如果在 classpath 路徑中)。
你可以輕鬆的爲你的 @ConfigurationProperties 類添加 JSR-303 javax.validation 約束註解:

@Component
@ConfigurationProperties(prefix="connection") public class ConnectionSettings {
@NotNull private InetAddress remoteAddress; // ... getters and setters
}


全局異常處理

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

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


以上內容轉自 螞蟻課堂

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章