Spring經常使用Annotation簡介

Annotation介紹


Spring項目開發經常使用Annotation

Java

@Resource

Resource 註釋標記應用程序所需的資源。此註釋能夠應用於應用程序組件類,或者該組件類的字段或方法。若是將該註釋應用於一個字段或方法,那麼初始化應用程序組件時容器將把所請求資源的一個實例注入其中。若是將該註釋應用於組件類,則該註釋將聲明一個應用程序在運行時將查找的資源。java

即便此註釋沒有被標記爲Inherited,部署工具仍然須要檢查任意組件類的全部超類,以發現這些超類中全部使用此註釋的地方。全部此類註釋實例都指定了應用程序組件所需的資源。注意,此註釋可能出如今超類的 private 字段和方法上;在這種狀況下容器也須要執行注入操做。web

在Spring中使用該註解,表示按name注入。spring

Spring

@Required

此註解用於JavaBean的setter方法上,表示此屬性是必須的,必須在配置階段注入,不然會拋出BeanInitializationException數據庫

@Autowired

此註解用於構造方法、字段、setter方法和註解類型。顯示聲明依賴,根據type來autowiring, 默認注入是必須的。api

@Target({ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Autowired {

    /**
     * Declares whether the annotated dependency is required.
     * <p>Defaults to {@code true}.
     */
    boolean required() default true;

}

在構造方法上使用此註解時,須要注意的是,一個類只容許有一個構造方法使用此註解。==此外,在Spring4.3後,若是一個類僅僅只有一個構造方法,那麼即便不使用此註解,spring也會自動注入相關的bean。==跨域

@Componentpublic class User {
    private Address address;
    public User(Address address) {
        this.address=address;     
    }
    
}

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

@Qualifier

此註解是和@Autowired一塊兒使用的。使用此註解可讓你對注入的過程有更多的控制,用@Qulifier指定要綁定的bean的名稱。當一個type有多個bean時,使用@Autowired的時候須要配合上@Qulifier才能正常。服務器

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

@Configuration

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

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

@Lazy

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

@Value

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

Stereotype註解

@Component

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

@Controller

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

@Service

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

@Repository

此類使用在class上聲明此類用於訪問數據庫,通常做爲DAO的角色。
此註解有自動翻譯的特性,例如:當此種component拋出了一個異常,那麼會有一個handler來處理此異常,無需使用try-catch塊。

Spring Boot註解

@EnableAutoConfiguration

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

@SpringBootApplication

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

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

  • @Configuration
  • @EnableAutoConfiguration
  • @ComponentScan

Spring MVC和REST註解

@Controller

上述已經提到過此註解。

@RequestMapping

此註解能夠用在class和method上,用來映射web請求到某一個handler類或者handler方法上。當此註解用在Class上時,就創造了一個基礎url,其全部的方法上的@RequestMapping都是在此url之上的。

可使用其method屬性來限制請求匹配的http method。

此外,Spring4.3以後引入了一系列@RequestMapping的變種。以下:c

  • @GetMapping
  • @PostMapping
  • @PutMapping
  • @PatchMapping
  • @DeleteMapping

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

@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" />

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

@Configurationpublic class WebConfig extends WebMvcConfigurerAdapter {     @Override    public void configurePathMatch(PathMatchConfigurer configurer) {        UrlPathHelper urlPathHelper = new UrlPathHelper();        urlPathHelper.setRemoveSemicolonContent(false);        configurer.setUrlPathHelper(urlPathHelper);    }}

@PathVariable

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

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

@RequestAttribute

此註解用在請求handler方法的參數上,用於將web請求中的屬性(requst 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, and @ModelAttribute處理。

@RestController

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

@RestControllerAdvice

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

@SessionAttribute

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

@SessionAttributes

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

@ModelAttribute("user")
public PUser getUser() {}

// controller和上面的代碼在同一controller中
@Controller
@SessionAttributes(value = "user", types = {
    User.class
})
public class UserController {}

數據訪問註解

@Transactional

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

任務執行、調度註解

@Scheduled

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

@Scheduled(fixedDelay=1000)
public void schedule() {}

@Scheduled(fixedRate=1000)
public void schedulg() {
}

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

@Async

此註解使用在方法上,聲明此方法會在一個單獨的線程中執行。不一樣於Scheduled註解,此註解能夠接受參數。
使用此註解的方法的返回類型能夠是Void也但是返回值。可是返回值的類型必須是一個Future。

測試註解

@ContextConfiguration

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

此註解通常須要搭配SpringJUnit4ClassRunner使用。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringCoreConfig.class)
public class UserServiceTest {}
相關文章
相關標籤/搜索