一、主要注解 (annotations) 一覽
@SpringBootApplication
:
包含了 @ComponentScan、@Configuration 和 @EnableAutoConfiguration 注解桦山。
其中 @ComponentScan 讓 spring Boot 掃描到 Configuration 類并把它加入到程序上下文峭跳。
@Configuration
等同于 spring 的 XML 配置文件唱矛;使用 Java 代碼可以檢查類型安全。
@EnableAutoConfiguration
自動配置培愁。
@ComponentScan
組件掃描著摔,可自動發(fā)現(xiàn)和裝配一些 Bean。
@Component
可配合 CommandLineRunner 使用定续,在程序啟動后執(zhí)行一些基礎任務谍咆。
@RestController
注解是 @Controller 和 @ResponseBody 的合集, 表示這是個控制器 bean, 并且是將函數(shù)的返回值直 接填入 HTTP 響應體中, 是 REST 風格的控制器。
@Autowired
自動導入私股。
@PathVariable
獲取參數(shù)摹察。
@JsonBackReference
解決嵌套外鏈問題。
@RepositoryRestResourcepublic
配合 spring-boot-starter-data-rest 使用倡鲸。
二供嚎、注解 (annotations) 詳解
- @SpringBootApplication:申明讓 spring boot 自動給程序進行必要的配置,這個配置等同于:@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);
}
}
- @ResponseBody:表示該方法的返回結(jié)果直接寫入 HTTP response body 中,一般在異步獲取數(shù)據(jù)時使用优床,用于構(gòu)建 RESTful 的 api劝赔。
在使用 @RequestMapping 后,返回值通常解析為跳轉(zhuǎn)路徑胆敞,加上 @responsebody 后返回結(jié)果不會被解析為跳轉(zhuǎn)路徑着帽,而是直接寫入 HTTP response body 中。
比如異步獲取 json 數(shù)據(jù)移层,加上 @responsebody 后仍翰,會直接返回 json 數(shù)據(jù)。
該注解一般會配合 @RequestMapping 一起使用幽钢。示例代碼:
@RequestMapping(“/test”)
@ResponseBody
public String test(){
return”ok”;
}
- @Controller:用于定義控制器類,在 spring 項目中由控制器負責將用戶發(fā)來的 URL 請求轉(zhuǎn)發(fā)到對應的服務接口(service 層)
一般這個注解在類中傅是,通常方法需要配合注解 @RequestMapping匪燕。
示例代碼:
@Controller
@RequestMapping(“/demoInfo”)
publicclass DemoController {
@Autowired
private DemoInfoService demoInfoService;
@RequestMapping("/hello")
public String hello(Map map){
System.out.println("DemoController.hello()");
map.put("hello","from TemplateController.helloHtml");
//會使用hello.html或者hello.ftl模板進行渲染顯示.
return"/hello";
}
}
- @RestController:用于標注控制層組件 (如 struts 中的 action)蕾羊,@ResponseBody 和 @Controller 的合集。
示例代碼:
package com.erbadagang.demo.web;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping(“/demoInfo2”)
publicclass DemoController2 {
@RequestMapping("/test")
public String test(){
return"ok";
}
}
- @RequestMapping:提供路由信息帽驯,負責 URL 到 Controller 中的具體函數(shù)的映射龟再。
- @EnableAutoConfiguration:Spring Boot 自動配置(auto-configuration):嘗試根據(jù)你添加的 jar 依賴自動配置你的 Spring 應用。
例如尼变,如果你的 classpath 下存在 HSQLDB利凑,并且你沒有手動配置任何數(shù)據(jù)庫連接 beans,那么我們將自動配置一個內(nèi)存型(in-memory)數(shù)據(jù)庫”嫌术。
你可以將 @EnableAutoConfiguration 或者 @SpringBootApplication 注解添加到一個 @Configuration 類上來選擇自動配置哀澈。
如果發(fā)現(xiàn)應用了你不想要的特定自動配置類,你可以使用 - @EnableAutoConfiguration 注解的排除屬性來禁用它們度气。
- @ComponentScan:表示將該類自動發(fā)現(xiàn)掃描組件割按。
個人理解相當于,如果掃描到有 @Component磷籍、@Controller适荣、@Service 等這些注解的類,并注冊為 Bean院领,可以自動收集所有的 Spring 組件弛矛,包括 - @Configuration 類。
我們經(jīng)常使用 @ComponentScan 注解搜索 beans比然,并結(jié)合 @Autowired 注解導入丈氓。可以自動收集所有的 Spring 組件谈秫,包括 @Configuration 類扒寄。
如果沒有配置的話,Spring Boot 會掃描啟動類所在包下以及子包下的使用了 @Service,@Repository 等注解的類拟烫。 - @Configuration:相當于傳統(tǒng)的 xml 配置文件该编,如果有些第三方庫需要用到 xml 文件,建議仍然通過 @Configuration 類作為項目的配置主類——可以使用 @ImportResource 注解加載 xml 配置文件硕淑。
- @Import:用來導入其他配置類课竣。
- @ImportResource:用來加載 xml 配置文件。
- @Autowired:自動導入依賴的 bean
- @Service:一般用于修飾 service 層的組件
- @Repository:使用 @Repository 注解可以確保 DAO 或者 repositories 提供異常轉(zhuǎn)譯置媳,這個注解修飾的 DAO 或者 repositories 類會被 ComponetScan 發(fā)現(xiàn)并配置于樟,同時也不需要為它們提供 XML 配置項。
- @Bean:用 @Bean 標注方法等價于 XML 中配置的 bean拇囊。
- @Value:注入 Spring boot application.properties 配置的屬性的值迂曲。示例代碼:
@Value(value = “#{message}”)
private String message;
- @Inject:等價于默認的 @Autowired,只是沒有 required 屬性寥袭;
- @Component:泛指組件路捧,當組件不好歸類的時候关霸,我們可以使用這個注解進行標注。
- @Bean:相當于 XML 中的, 放在方法的上面杰扫,而不是類队寇,意思是產(chǎn)生一個 bean, 并交給 spring 管理。
- @AutoWired:自動導入依賴的 bean章姓。byType 方式佳遣。把配置好的 Bean 拿來用,完成屬性凡伊、方法的組裝零渐,它可以對類成員變量、方法及構(gòu)造函數(shù)進行標注窗声,完成自動裝配的工作相恃。當加上(required=false)時,就算找不到 bean 也不報錯笨觅。
- @Qualifier:當有多個同一類型的 Bean 時拦耐,可以用 @Qualifier(“name”) 來指定。與 @Autowired 配合使用见剩。@Qualifier 限定描述符除了能根據(jù)名字進行注入杀糯,但能進行更細粒度的控制如何選擇候選者,具體使用方式如下:
@Autowired
@Qualifier(value = “demoInfoService”)
private DemoInfoService demoInfoService;
- @Resource(name=”name”,type=”type”):沒有括號內(nèi)內(nèi)容的話苍苞,默認 byName固翰。與 @Autowired 干類似的事。
三羹呵、JPA 注解
- @Entity:@Table(name=”“):表明這是一個實體類骂际。一般用于 jpa 這兩個注解一般一塊使用,但是如果表名和實體類名相同的話冈欢,@Table 可以省略
- @MappedSuperClass: 用在確定是父類的 entity 上歉铝。父類的屬性子類可以繼承。
- @NoRepositoryBean: 一般用作父類的 repository凑耻,有這個注解太示,spring 不會去實例化該 repository。
- @Column:如果字段名與列名相同香浩,則可以省略类缤。
- @Id:表示該屬性為主鍵。
- @GeneratedValue(strategy=GenerationType.SEQUENCE,generator= “repair_seq”):表示主鍵生成策略是 sequence(可以為 Auto邻吭、IDENTITY餐弱、native 等,Auto 表示可在多個數(shù)據(jù)庫間切換),指定 sequence 的名字是 repair_seq膏蚓。
- @SequenceGeneretor(name = “repair_seq”, sequenceName = “seq_repair”, allocationSize = 1):name 為 sequence 的名稱猖败,以便使用,sequenceName 為數(shù)據(jù)庫的 sequence 名稱降允,兩個名稱可以一致。
- @Transient:表示該屬性并非一個到數(shù)據(jù)庫表的字段的映射, ORM 框架將忽略該屬性艺糜。
如果一個屬性并非數(shù)據(jù)庫表的字段映射, 就務必將其標示為 @Transient, 否則, ORM 框架默認其注解為 @Basic剧董。@Basic(fetch=FetchType.LAZY):標記可以指定實體屬性的加載方式 - @JsonIgnore:作用是 json 序列化時將 Java bean 中的一些屬性忽略掉, 序列化和反序列化都受影響。
- @JoinColumn(name=”loginId”): 一對一:本表中指向另一個表的外鍵破停。一對多:另一個表指向本表的外鍵翅楼。
- @OneToOne、@OneToMany真慢、@ManyToOne:對應 hibernate 配置文件中的一對一毅臊,一對多,多對一黑界。
四管嬉、springMVC 相關注解
- @RequestMapping:@RequestMapping(“/path”)表示該控制器處理所有 “/path” 的 UR L 請求。
RequestMapping 是一個用來處理請求地址映射的注解朗鸠,可用于類或方法上蚯撩。
用于類上,表示類中的所有響應請求的方法都是以該地址作為父路徑烛占。
該注解有六個屬性:
params: 指定 request 中必須包含某些參數(shù)值是胎挎,才讓該方法處理。
headers: 指定 request 中必須包含某些指定的 header 值忆家,才能讓該方法處理請求犹菇。
value: 指定請求的實際地址,指定的地址可以是 URI Template 模式
method: 指定請求的 method 類型芽卿, GET揭芍、POST、PUT蹬竖、DELETE 等
consumes: 指定處理請求的提交內(nèi)容類型(Content-Type)沼沈,如 application/json,text/html;
produces: 指定返回的內(nèi)容類型,僅當 request 請求頭中的 (Accept) 類型中包含該指定類型才返回
@RequestParam:用在方法的參數(shù)前面币厕。 - @RequestParam
String a =request.getParameter(“a”)列另。 - @PathVariable: 路徑變量。如
RequestMapping(“user/get/mac/{macAddress}”)
public String getByMacAddress(@PathVariable String macAddress){
//do something;
}
參數(shù)與大括號里的名字一樣要相同旦装。
五页衙、全局異常處理
- @ControllerAdvice:包含 @Component。可以被掃描到店乐。統(tǒng)一處理異常艰躺。
- @ExceptionHandler(Exception.class):用在方法上面表示遇到這個異常就執(zhí)行以下方法。