spring中最常用的7大類注解

隨著技術(shù)的更新迭代,Java5.0開始支持注解。而作為java中的領(lǐng)軍框架spring,自從更新了2.5版本之后也開始慢慢舍棄xml配置,更多使用注解來控制spring框架。
而spring的的注解那么多,可能做java很多年,都用不上。這里按照類型總結(jié)了這7種最常用的注解。
一. 核心注解
@Required
此注解用于bean的setter方法上。表示此屬性是必須的,必須在配置階段注入,否則會拋出BeanInitializationExcepion。
@Autowired
此注解用于bean的field、setter方法以及構(gòu)造方法上,顯式地聲明依賴。根據(jù)type來autowiring。
當在field上使用此注解,并且使用屬性來傳遞值時,Spring會自動把值賦給此field。也可以將此注解用于私有屬性(不推薦),如下。
@Component
public class User {
@Autowired
private Address address;
}
最經(jīng)常的用法是將此注解用于settter上,這樣可以在setter方法中添加自定義代碼。如下:
@Component
public class User {
private Address address;
@AutoWired
public setAddress(Address address) {
// custom code
this.address=address;
}
}
當在構(gòu)造方法上使用此注解的時候,需要注意的一點就是一個類中只允許有一個構(gòu)造方法使用此注解。此外,在Spring4.3后,如果一個類僅僅只有一個構(gòu)造方法,那么即使不使用此注解,那么Spring也會自動注入相關(guān)的bean。如下:
@Component
public class User {
private Address address;
public User(Address address) {
this.address=address;
}
}
<bean id="user" class="xx.User"/>
@Qualifier
此注解是和@Autowired一起使用的。使用此注解可以讓你對注入的過程有更多的控制。
@Qualifier可以被用在單個構(gòu)造器或者方法的參數(shù)上。當上下文有幾個相同類型的bean, 使用@Autowired則無法區(qū)分要綁定的bean,此時可以使用@Qualifier來指定名稱。
@Component
public class User {
@Autowired
@Qualifier("address1")
private Address address;
...
}
@Configuration
此注解用在class上來定義bean。其作用和xml配置文件相同,表示此bean是一個Spring配置。此外,此類可以使用@Bean注解來初始化定義bean。
@Configuartion
public class SpringCoreConfig {
@Bean
public AdminUser adminUser() {
AdminUser adminUser = new AdminUser();
return adminUser;
}
}
@ComponentScan
此注解一般和@Configuration注解一起使用,指定Spring掃描注解的package。如果沒有指定包,那么默認會掃描此配置類所在的package。
@Lazy
此注解使用在Spring的組件類上。默認的,Spring中Bean的依賴一開始就被創(chuàng)建和配置。如果想要延遲初始化一個bean,那么可以在此類上使用Lazy注解,表示此bean只有在第一次被使用的時候才會被創(chuàng)建和初始化。此注解也可以使用在被@Configuration注解的類上,表示其中所有被@Bean注解的方法都會延遲初始化。
@Value
此注解使用在字段、構(gòu)造器參數(shù)和方法參數(shù)上。@Value可以指定屬性取值的表達式,支持通過#{}使用SpringEL來取值,也支持使用${}來將屬性來源中(Properties文件、本地環(huán)境變量、系統(tǒng)屬性等)的值注入到bean的屬性中。此注解值的注入發(fā)生在AutowiredAnnotationBeanPostProcessor類中。
二. Spring MVC和REST注解
@Controller
此注解使用在class上聲明此類是一個Spring controller,是@Component注解的一種具體形式。
@RequestMapping
此注解可以用在class和method上,用來映射web請求到某一個handler類或者handler方法上。當此注解用在Class上時,就創(chuàng)造了一個基礎(chǔ)url,其所有的方法上的@RequestMapping都是在此url之上的。
可以使用其method屬性來限制請求匹配的http method。
@Controller
@RequestMapping("/users")
public class UserController {
@RequestMapping(method = RequestMethod.GET)
public String getUserList() {
return "users";
}
}
此外,Spring4.3之后引入了一系列@RequestMapping的變種。如下:
@GetMapping
@PostMapping
@PutMapping
@PatchMapping
@DeleteMapping
分別對應(yīng)了相應(yīng)method的RequestMapping配置。
@CookieValue
此注解用在@RequestMapping聲明的方法的參數(shù)上,可以把HTTP cookie中相應(yīng)名稱的cookie綁定上去。
@ReuestMapping("/cookieValue")
public void getCookieValue(@CookieValue("JSESSIONID") String cookie){
}
cookie即http請求中name為JSESSIONID的cookie值。
@CrossOrigin
此注解用在class和method上用來支持跨域請求,是Spring 4.2后引入的。
@CrossOrigin(maxAge = 3600)
@RestController
@RequestMapping("/users")
public class AccountController {
@CrossOrigin(origins = "http://xx.com")
@RequestMapping("/login")
public Result userLogin() {
// ...
}
}
@ExceptionHandler
此注解使用在方法級別,聲明對Exception的處理邏輯??梢灾付繕薊xception。
@InitBinder
此注解使用在方法上,聲明對WebDataBinder的初始化(綁定請求參數(shù)到JavaBean上的DataBinder)。在controller上使用此注解可以自定義請求參數(shù)的綁定。
@MatrixVariable
此注解使用在請求handler方法的參數(shù)上,Spring可以注入matrix url中相關(guān)的值。這里的矩陣變量可以出現(xiàn)在url中的任何地方,變量之間用;分隔。如下:
// GET /pets/42;q=11;r=22
@RequestMapping(value = "/pets/{petId}")
public void findPet(@PathVariable String petId, @MatrixVariable int q) {
// petId == 42
// q == 11
}
需要注意的是默認Spring mvc是不支持矩陣變量的,需要開啟。
<mvc:annotation-driven enable-matrix-variables="true" />
注解配置則需要如下開啟:
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
UrlPathHelper urlPathHelper = new UrlPathHelper();
urlPathHelper.setRemoveSemicolonContent(false);
configurer.setUrlPathHelper(urlPathHelper);
}
}
@PathVariable
此注解使用在請求handler方法的參數(shù)上。@RequestMapping可以定義動態(tài)路徑,如:
@RequestMapping("/users/{uid}")
可以使用@PathVariable將路徑中的參數(shù)綁定到請求方法參數(shù)上。
@RequestMapping("/users/{uid}")
public String execute(@PathVariable("uid") String uid){
}
@RequestAttribute
此注解用在請求handler方法的參數(shù)上,用于將web請求中的屬性(request attributes,是服務(wù)器放入的屬性值)綁定到方法參數(shù)上。
@RequestBody
此注解用在請求handler方法的參數(shù)上,用于將http請求的Body映射綁定到此參數(shù)上。HttpMessageConverter負責將對象轉(zhuǎn)換為http請求。
@RequestHeader
此注解用在請求handler方法的參數(shù)上,用于將http請求頭部的值綁定到參數(shù)上。
@RequestParam
此注解用在請求handler方法的參數(shù)上,用于將http請求參數(shù)的值綁定到參數(shù)上。
@RequestPart
此注解用在請求handler方法的參數(shù)上,用于將文件之類的multipart綁定到參數(shù)上。
@ResponseBody
此注解用在請求handler方法上。和@RequestBody作用類似,用于將方法的返回對象直接輸出到http響應(yīng)中。
@ResponseStatus
此注解用于方法和exception類上,聲明此方法或者異常類返回的http狀態(tài)碼??梢栽贑ontroller上使用此注解,這樣所有的@RequestMapping都會繼承。
@ControllerAdvice
此注解用于class上。前面說過可以對每一個controller聲明一個ExceptionMethod。這里可以使用@ControllerAdvice來聲明一個類來統(tǒng)一對所有@RequestMapping方法來做@ExceptionHandler、@InitBinder以及@ModelAttribute處理。
@RestController
此注解用于class上,聲明此controller返回的不是一個視圖而是一個領(lǐng)域?qū)ο蟆F渫瑫r引入了@Controller和@ResponseBody兩個注解。
@RestControllerAdvice
此注解用于class上,同時引入了@ControllerAdvice和@ResponseBody兩個注解。
@SessionAttribute
此注解用于方法的參數(shù)上,用于將session中的屬性綁定到參數(shù)。
@SessionAttributes
此注解用于type級別,用于將JavaBean對象存儲到session中。一般和@ModelAttribute注解一起使用。如下:
@ModelAttribute("user")
public PUser getUser() {}
// controller和上面的代碼在同一controller中
@Controller
@SeesionAttributes(value = "user", types = {
User.class
})
public class UserController {}
三. Spring Boot注解
@EnableAutoConfiguration
此注解通常被用在主應(yīng)用class上,告訴Spring Boot自動基于當前包添加Bean、對bean的屬性進行設(shè)置等。
@SpringBootApplication
此注解用在Spring Boot項目的應(yīng)用主類上(此類需要在base package中)。使用了此注解的類首先會讓Spring Boot啟動對base package以及其sub-pacakage下的類進行component scan。
此注解同時添加了以下幾個注解:
@Configuration
@EnableAutoConfiguration
@ComponentScan
四. Stereotype注解
@Component
此注解使用在class上來聲明一個Spring組件(Bean), 將其加入到應(yīng)用上下文中。
@Controller
前文已經(jīng)提到過
@Service
此注解使用在class上,聲明此類是一個服務(wù)類,執(zhí)行業(yè)務(wù)邏輯、計算、調(diào)用內(nèi)部api等。是@Component注解的一種具體形式。
@Repository
此類使用在class上聲明此類用于訪問數(shù)據(jù)庫,一般作為DAO的角色。
此注解有自動翻譯的特性,例如:當此種component拋出了一個異常,那么會有一個handler來處理此異常,無需使用try-catch塊。
五. 數(shù)據(jù)訪問注解
@Transactional
此注解使用在接口定義、接口中的方法、類定義或者類中的public方法上。需要注意的是此注解并不激活事務(wù)行為,它僅僅是一個元數(shù)據(jù),會被一些運行時基礎(chǔ)設(shè)施來消費。
六. 任務(wù)執(zhí)行、調(diào)度注解
@Scheduled
此注解使用在方法上,聲明此方法被定時調(diào)度。使用了此注解的方法返回類型需要是Void,并且不能接受任何參數(shù)。
@Scheduled(fixedDelay=1000)
public void schedule() {
}
@Scheduled(fixedRate=1000)
public void schedulg() {
}
第二個與第一個不同之處在于其不會等待上一次的任務(wù)執(zhí)行結(jié)束。
@Async
此注解使用在方法上,聲明此方法會在一個單獨的線程中執(zhí)行。不同于Scheduled注解,此注解可以接受參數(shù)。
使用此注解的方法的返回類型可以是Void也可是返回值。但是返回值的類型必須是一個Future。
七. 測試注解
@ContextConfiguration
此注解使用在Class上,聲明測試使用的配置文件,此外,也可以指定加載上下文的類。
此注解一般需要搭配SpringJUnit4ClassRunner使用。
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringCoreConfig.class)
public class UserServiceTest {
}