1. 程式人生 > >Spring Boot 常用註解彙總

Spring Boot 常用註解彙總

Spring Boot 常用註解彙總

一、啟動註解 @SpringBootApplication

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
        @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {
    // ... 此處省略原始碼
}

檢視原始碼可發現,@SpringBootApplication是一個複合註解,包含了@SpringBootConfiguration,@EnableAutoConfiguration,@ComponentScan這三個註解

@SpringBootConfiguration 註解,繼承@Configuration註解,主要用於載入配置檔案

@SpringBootConfiguration繼承自@Configuration,二者功能也一致,標註當前類是配置類, 並會將當前類內宣告的一個或多個以@Bean註解標記的方法的例項納入到spring容器中,並且例項名就是方法名。

@EnableAutoConfiguration 註解,開啟自動配置功能

@EnableAutoConfiguration可以幫助SpringBoot應用將所有符合條件的@Configuration配置都載入到當前SpringBoot建立並使用的IoC容器。藉助於Spring框架原有的一個工具類:SpringFactoriesLoader的支援,@EnableAutoConfiguration可以智慧的自動配置功效才得以大功告成

@ComponentScan 註解,主要用於元件掃描和自動裝配

@ComponentScan的功能其實就是自動掃描並載入符合條件的元件或bean定義,最終將這些bean定義載入到容器中。我們可以通過basePackages等屬性指定@ComponentScan自動掃描的範圍,如果不指定,則預設Spring框架實現從宣告@ComponentScan所在類的package進行掃描,預設情況下是不指定的,所以SpringBoot的啟動類最好放在root package下。

二、Controller 相關注解

@Controller

控制器,處理http請求。

@RestController 複合註解

檢視@RestController原始碼

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController {

    /**
     * The value may indicate a suggestion for a logical component name,
     * to be turned into a Spring bean in case of an autodetected component.
     * @return the suggested component name, if any (or empty String otherwise)
     * @since 4.0.1
     */
    @AliasFor(annotation = Controller.class)
    String value() default "";
}

從原始碼我們知道,@RestController註解相當於@ResponseBody+@Controller合在一起的作用,RestController使用的效果是將方法返回的物件直接在瀏覽器上展示成json格式.

@RequestBody

通過HttpMessageConverter讀取Request Body並反序列化為Object(泛指)物件

@RequestMapping

@RequestMapping 是 Spring Web 應用程式中最常被用到的註解之一。這個註解會將 HTTP 請求對映到 MVC 和 REST 控制器的處理方法上

@GetMapping用於將HTTP get請求對映到特定處理程式的方法註解

註解簡寫:@RequestMapping(value = "/say",method = RequestMethod.GET)等價於:@GetMapping(value = "/say")

GetMapping原始碼

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@RequestMapping(method = RequestMethod.GET)
public @interface GetMapping {
//...
}

是@RequestMapping(method = RequestMethod.GET)的縮寫

@PostMapping用於將HTTP post請求對映到特定處理程式的方法註解

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@RequestMapping(method = RequestMethod.POST)
public @interface PostMapping {
    //...
}

是@RequestMapping(method = RequestMethod.POST)的縮寫

三、取請求引數值

@PathVariable:獲取url中的資料

@Controller
@RequestMapping("/User")
public class HelloWorldController {

    @RequestMapping("/getUser/{uid}")
    public String getUser(@PathVariable("uid")Integer id, Model model) {
        System.out.println("id:"+id);
        return "user";
    }
}

請求示例:http://localhost:8080/User/getUser/123

@RequestParam:獲取請求引數的值

@Controller
@RequestMapping("/User")
public class HelloWorldController {

@RequestMapping("/getUser")
public String getUser(@RequestParam("uid")Integer id, Model model) {
    System.out.println("id:"+id);
    return "user";
}

}

請求示例:http://localhost:8080/User/getUser?uid=123

@RequestHeader 把Request請求header部分的值繫結到方法的引數上

@CookieValue 把Request header中關於cookie的值繫結到方法的引數上

四、注入bean相關

@Repository

DAO層註解,DAO層中介面繼承JpaRepository<T,ID extends Serializable>,需要在build.gradle中引入相關jpa的一個jar自動載入。

Repository註解原始碼

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Repository {

    /**
     * The value may indicate a suggestion for a logical component name,
     * to be turned into a Spring bean in case of an autodetected component.
     * @return the suggested component name, if any (or empty String otherwise)
     */
    @AliasFor(annotation = Component.class)
    String value() default "";

}

@Service

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Service {

    /**
     * The value may indicate a suggestion for a logical component name,
     * to be turned into a Spring bean in case of an autodetected component.
     * @return the suggested component name, if any (or empty String otherwise)
     */
    @AliasFor(annotation = Component.class)
    String value() default "";
}
  • @Service是@Component註解的一個特例,作用在類上
  • @Service註解作用域預設為單例
  • 使用註解配置和類路徑掃描時,被@Service註解標註的類會被Spring掃描並註冊為Bean
  • @Service用於標註服務層元件,表示定義一個bean
  • @Service使用時沒有傳引數,Bean名稱預設為當前類的類名,首字母小寫
  • @Service(“serviceBeanId”)或@Service(value=”serviceBeanId”)使用時傳引數,使用value作為Bean名字

@Scope作用域註解

@Scope作用在類上和方法上,用來配置 spring bean 的作用域,它標識 bean 的作用域

@Scope原始碼

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Scope {

    /**
     * Alias for {@link #scopeName}.
     * @see #scopeName
     */
    @AliasFor("scopeName")
    String value() default "";

    @AliasFor("value")
    String scopeName() default "";

    ScopedProxyMode proxyMode() default ScopedProxyMode.DEFAULT;
}

屬性介紹

value
    singleton   表示該bean是單例的。(預設)
    prototype   表示該bean是多例的,即每次使用該bean時都會新建一個物件。
    request     在一次http請求中,一個bean對應一個例項。
    session     在一個httpSession中,一個bean對應一個例項。
    
proxyMode
    DEFAULT         不使用代理。(預設)
    NO              不使用代理,等價於DEFAULT。
    INTERFACES      使用基於介面的代理(jdk dynamic proxy)。
    TARGET_CLASS    使用基於類的代理(cglib)。

@Entity實體類註解

@Table(name ="資料庫表名"),這個註解也註釋在實體類上,對應資料庫中相應的表。
@Id、@Column註解用於標註實體類中的欄位,pk欄位標註為@Id,其餘@Column。

@Bean產生一個bean的方法

@Bean明確地指示了一種方法,產生一個bean的方法,並且交給Spring容器管理。支援別名@Bean("xx-name")

@Autowired 自動匯入

  • @Autowired註解作用在建構函式、方法、方法引數、類欄位以及註解上
  • @Autowired註解可以實現Bean的自動注入

@Component

把普通pojo例項化到spring容器中,相當於配置檔案中的

雖然有了@Autowired,但是我們還是要寫一堆bean的配置檔案,相當麻煩,而@Component就是告訴spring,我是pojo類,把我註冊到容器中吧,spring會自動提取相關資訊。那麼我們就不用寫麻煩的xml配置檔案了

五、匯入配置檔案

@PropertySource註解

引入單個properties檔案:

@PropertySource(value = {"classpath : xxxx/xxx.properties"})

引入多個properties檔案:

@PropertySource(value = {"classpath : xxxx/xxx.properties","classpath : xxxx.properties"})

@ImportResource匯入xml配置檔案

可以額外分為兩種模式 相對路徑classpath,絕對路徑(真實路徑)file

注意:單檔案可以不寫value或locations,value和locations都可用

相對路徑(classpath)

  • 引入單個xml配置檔案:@ImportSource("classpath : xxx/xxxx.xml")

  • 引入多個xml配置檔案:@ImportSource(locations={"classpath : xxxx.xml" , "classpath : yyyy.xml"})

絕對路徑(file)

  • 引入單個xml配置檔案:@ImportSource(locations= {"file : d:/hellxz/dubbo.xml"})

  • 引入多個xml配置檔案:@ImportSource(locations= {"file : d:/hellxz/application.xml" , "file : d:/hellxz/dubbo.xml"})

取值:使用@Value註解取配置檔案中的值

@Value("${properties中的鍵}")
private String xxx;

@Import 匯入額外的配置資訊

功能類似XML配置的,用來匯入配置類,可以匯入帶有@Configuration註解的配置類或實現了ImportSelector/ImportBeanDefinitionRegistrar。

使用示例

@SpringBootApplication
@Import({SmsConfig.class})
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

六、事務註解 @Transactional

在Spring中,事務有兩種實現方式,分別是程式設計式事務管理和宣告式事務管理兩種方式

  • 程式設計式事務管理: 程式設計式事務管理使用TransactionTemplate或者直接使用底層的PlatformTransactionManager。對於程式設計式事務管理,spring推薦使用TransactionTemplate。
  • 宣告式事務管理: 建立在AOP之上的。其本質是對方法前後進行攔截,然後在目標方法開始之前建立或者加入一個事務,在執行完目標方法之後根據執行情況提交或者回滾事務,通過@Transactional就可以進行事務操作,更快捷而且簡單。推薦使用

七、全域性異常處理

@ControllerAdvice 統一處理異常

@ControllerAdvice 註解定義全域性異常處理類

@ControllerAdvice
public class GlobalExceptionHandler {
}

@ExceptionHandler 註解宣告異常處理方法

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseBody
    String handleException(){
        return "Exception Deal!";
    }
}

八、資料

  • Java問題收集
  • 原文地址