Spring 最經常使用的 7 大類註解,史上最強整理!

隨着技術的更新迭代,Java5.0開始支持註解。而做爲java中的領軍框架spring,自從更新了2.5版本以後也開始慢慢捨棄xml配置,更多使用註解來控制spring框架。
java

而spring的的註解那麼多,可能作java不少年,都用不上。這裏按照類型總結了這7種最經常使用的註解。web

一. 核心註解

@Required
此註解用於bean的setter方法上。表示此屬性是必須的,必須在配置階段注入,不然會拋出BeanInitializationExcepion。spring

@Autowired
此註解用於bean的field、setter方法以及構造方法上,顯式地聲明依賴。根據type來autowiring。數據庫

當在field上使用此註解,而且使用屬性來傳遞值時,Spring會自動把值賦給此field。也能夠將此註解用於私有屬性(不推薦),以下。api

@Componentpublic class User {    @Autowired                                   private Address address;                   }

最常常的用法是將此註解用於settter上,這樣能夠在setter方法中添加自定義代碼。以下:跨域

 
 
  1. @Component服務器

  2. public class User {cookie

  3.     private Address address;session


  4.     @AutoWiredmvc

  5.   public setAddress(Address address) {

  6.      // custom code

  7.      this.address=address;

  8.   }

  9. }

當在構造方法上使用此註解的時候,須要注意的一點就是一個類中只容許有一個構造方法使用此註解。此外,在Spring4.3後,若是一個類僅僅只有一個構造方法,那麼即便不使用此註解,那麼Spring也會自動注入相關的bean。以下:

 
 
  1. @Component

  2. public class User {

  3.    private Address address;


  4.     public User(Address address) {      

  5.        this.address=address;

  6.     }

  7. }


  8. <bean id="user" class="xx.User"/>

@Qualifier
此註解是和@Autowired一塊兒使用的。使用此註解可讓你對注入的過程有更多的控制。

@Qualifier能夠被用在單個構造器或者方法的參數上。當上下文有幾個相同類型的bean, 使用@Autowired則沒法區分要綁定的bean,此時能夠使用@Qualifier來指定名稱。

@Componentpublic class User {    @Autowired    @Qualifier("address1")    private Address address;    ...}

@Configuration
此註解用在class上來定義bean。其做用和xml配置文件相同,表示此bean是一個Spring配置。此外,此類能夠使用@Bean註解來初始化定義bean。

@Configuartionpublic class SpringCoreConfig {    @Bean    public AdminUser adminUser() {        AdminUser adminUser = new AdminUser();        return adminUser;    }}

@ComponentScan
此註解通常和@Configuration註解一塊兒使用,指定Spring掃描註解的package。若是沒有指定包,那麼默認會掃描此配置類所在的package。

@Lazy
此註解使用在Spring的組件類上。默認的,Spring中Bean的依賴一開始就被建立和配置。若是想要延遲初始化一個bean,那麼能夠在此類上使用Lazy註解,表示此bean只有在第一次被使用的時候纔會被建立和初始化。此註解也能夠使用在被@Configuration註解的類上,表示其中全部被@Bean註解的方法都會延遲初始化。

@Value
此註解使用在字段、構造器參數和方法參數上。@Value能夠指定屬性取值的表達式,支持經過#{}使用SpringEL來取值,也支持使用${}來將屬性來源中(Properties文件、本地環境變量、系統屬性等)的值注入到bean的屬性中。此註解值的注入發生在AutowiredAnnotationBeanPostProcessor類中。

二. Spring MVC和REST註解

@Controller
此註解使用在class上聲明此類是一個Spring controller,是@Component註解的一種具體形式。

@RequestMapping
此註解能夠用在class和method上,用來映射web請求到某一個handler類或者handler方法上。當此註解用在Class上時,就創造了一個基礎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

分別對應了相應method的RequestMapping配置。

@CookieValue
此註解用在@RequestMapping聲明的方法的參數上,能夠把HTTP cookie中相應名稱的cookie綁定上去。

 
 
  1. @ReuestMapping("/cookieValue")

  2.      public void getCookieValue(@CookieValue("JSESSIONID") String cookie){


  3. }

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的處理邏輯。能夠指定目標Exception。

@InitBinder
此註解使用在方法上,聲明對WebDataBinder的初始化(綁定請求參數到JavaBean上的DataBinder)。在controller上使用此註解能夠自定義請求參數的綁定。

@MatrixVariable
此註解使用在請求handler方法的參數上,Spring能夠注入matrix url中相關的值。這裏的矩陣變量能夠出如今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" />

註解配置則須要以下開啓:

 
 
  1. @Configuration

  2. public class WebConfig extends WebMvcConfigurerAdapter {


  3.    @Override

  4.    public void configurePathMatch(PathMatchConfigurer configurer) {

  5.        UrlPathHelper urlPathHelper = new UrlPathHelper();

  6.        urlPathHelper.setRemoveSemicolonContent(false);

  7.        configurer.setUrlPathHelper(urlPathHelper);

  8.    }

  9. }

@PathVariable
此註解使用在請求handler方法的參數上。@RequestMapping能夠定義動態路徑,如:

@RequestMapping("/users/{uid}")

能夠使用@PathVariable將路徑中的參數綁定到請求方法參數上。

@RequestMapping("/users/{uid}")public String execute(@PathVariable("uid") String uid){}@RequestAttribute

此註解用在請求handler方法的參數上,用於將web請求中的屬性(request attributes,是服務器放入的屬性值)綁定到方法參數上。

@RequestBody
此註解用在請求handler方法的參數上,用於將http請求的Body映射綁定到此參數上。HttpMessageConverter負責將對象轉換爲http請求。

@RequestHeader
此註解用在請求handler方法的參數上,用於將http請求頭部的值綁定到參數上。

@RequestParam
此註解用在請求handler方法的參數上,用於將http請求參數的值綁定到參數上。

@RequestPart
此註解用在請求handler方法的參數上,用於將文件之類的multipart綁定到參數上。

@ResponseBody
此註解用在請求handler方法上。和@RequestBody做用相似,用於將方法的返回對象直接輸出到http響應中。

@ResponseStatus
此註解用於方法和exception類上,聲明此方法或者異常類返回的http狀態碼。能夠在Controller上使用此註解,這樣全部的@RequestMapping都會繼承。

@ControllerAdvice
此註解用於class上。前面說過能夠對每個controller聲明一個ExceptionMethod。這裏能夠使用@ControllerAdvice來聲明一個類來統一對全部@RequestMapping方法來作@ExceptionHandler、@InitBinder以及@ModelAttribute處理。

@RestController
此註解用於class上,聲明此controller返回的不是一個視圖而是一個領域對象。其同時引入了@Controller和@ResponseBody兩個註解。

@RestControllerAdvice
此註解用於class上,同時引入了@ControllerAdvice和@ResponseBody兩個註解。

@SessionAttribute
此註解用於方法的參數上,用於將session中的屬性綁定到參數。

@SessionAttributes
此註解用於type級別,用於將JavaBean對象存儲到session中。通常和@ModelAttribute註解一塊兒使用。以下:

 
 
  1. @ModelAttribute("user")


  2. public PUser getUser() {}


  3. // controller和上面的代碼在同一controller中

  4. @Controller

  5. @SeesionAttributes(value = "user", types = {

  6.    User.class

  7. })


  8. public class UserController {}

三. Spring Boot註解

@EnableAutoConfiguration
此註解一般被用在主應用class上,告訴Spring Boot自動基於當前包添加Bean、對bean的屬性進行設置等。

@SpringBootApplication
此註解用在Spring Boot項目的應用主類上(此類須要在base package中)。使用了此註解的類首先會讓Spring Boot啓動對base package以及其sub-pacakage下的類進行component scan。

此註解同時添加了如下幾個註解:

  • @Configuration

  • @EnableAutoConfiguration

  • @ComponentScan

四. Stereotype註解

@Component
此註解使用在class上來聲明一個Spring組件(Bean), 將其加入到應用上下文中。

@Controller
前文已經提到過

@Service
此註解使用在class上,聲明此類是一個服務類,執行業務邏輯、計算、調用內部api等。是@Component註解的一種具體形式。

@Repository
此類使用在class上聲明此類用於訪問數據庫,通常做爲DAO的角色。

此註解有自動翻譯的特性,例如:當此種component拋出了一個異常,那麼會有一個handler來處理此異常,無需使用try-catch塊。

五. 數據訪問註解

@Transactional
此註解使用在接口定義、接口中的方法、類定義或者類中的public方法上。須要注意的是此註解並不激活事務行爲,它僅僅是一個元數據,會被一些運行時基礎設施來消費。

六. 任務執行、調度註解

@Scheduled
此註解使用在方法上,聲明此方法被定時調度。使用了此註解的方法返回類型須要是Void,而且不能接受任何參數。

 
 
  1. @Scheduled(fixedDelay=1000)

  2. public void schedule() {


  3. }


  4. @Scheduled(fixedRate=1000)

  5. public void schedulg() {


  6. }

第二個與第一個不一樣之處在於其不會等待上一次的任務執行結束。

@Async
此註解使用在方法上,聲明此方法會在一個單獨的線程中執行。不一樣於Scheduled註解,此註解能夠接受參數。

使用此註解的方法的返回類型能夠是Void也但是返回值。可是返回值的類型必須是一個Future。

七. 測試註解

@ContextConfiguration
此註解使用在Class上,聲明測試使用的配置文件,此外,也能夠指定加載上下文的類。

此註解通常須要搭配SpringJUnit4Cla***unner使用。

 
 
  1. @RunWith(SpringJUnit4Cla***unner.class)

  2. @ContextConfiguration(classes = SpringCoreConfig.class)

  3. public class UserServiceTest {


  4. }



做者:Java高級開發之路

blog.csdn.net/Lubanjava/article/details/100579554

相關文章
相關標籤/搜索