SpringBoot 常用注解


一、Spring MVC 相關注解

1、@RequestMapping

(1)功能:
  將 HTTP 請求 與 請求處理類中的方法 進行映射。
  通過 RequestMappingHandlerMapping 與 RequestMappingHandlerAdapter 兩個類來支持該注解。

(2)常用參數:
  value: 用於保存請求的 URL
  method: 用於指定當前請求的方法,比如:PUT,GET,DELETE,POST 等。

(3)用法舉例:
  使用之前需要 通過 @RestController 或者 @Controller 注解標記類。
如下例所示:
  @RequestMapping 可以對類、方法進行標記,使用時會自動拼接。
  並根據不同的請求方法(method),找到相對應的請求處理方法。

@RestController
@RequestMapping("/api")
public class EmpController {

    @RequestMapping(value = "/emp/{id}", method = RequestMethod.GET)
    public Result selectOne(@PathVariable(name = "id") Integer id) {
        return Result.ok();
    }
    
    @RequestMapping(value = "/emp", method = RequestMethod.POST)
    public Result createEmp(@RequestBody Emp emp) {
        return Result.ok();
    }
    
    @RequestMapping(value = "/emp{id}", method = RequestMethod.DELETE)
    public Result deleteById(@PathVariable(name = "id") Integer id) {
        return Result.ok();
    }
    
    @RequestMapping(value = "/emp{id}", method = RequestMethod.PUT)
    public Result updateEmp(@PathVariable(name = "id") Integer id, @RequestBody Emp emp) {
        return Result.ok();
    }
}

 

2、@GetMapping

(1)功能:
  用於處理 HTTP 的 GET 請求。
  本質是 @RequestMapping(method = RequestMethod.GET)。

(2)舉例:
  @RequestMapping(value = "/emp/{id}", method = RequestMethod.GET)
等價於
  @GetMapping("/emp/{id}")

@RestController
@RequestMapping("/api")
public class EmpController {

    @GetMapping("/emp/{id}")
    public Result selectOne(@PathVariable(name="id") Integer id) {
        return Result.ok();
    }

}

 

3、@PostMapping

(1)功能:
  用於處理 HTTP 的 POST 請求。
  本質是 @RequestMapping(method = RequestMethod.POST)。

(2)舉例:
  @RequestMapping(value = "/emp", method = RequestMethod.POST)
等價於
  @PostMapping("/emp")

@RestController
@RequestMapping("/api")
public class EmpController {

    @PostMapping("/emp")
    public Result createEmp(@RequestBody Emp emp) {
        return Result.ok();
    }

}

 

4、@PutMapping

(1)功能:
  用於處理 HTTP 的 PUT 請求。
  本質是:@RequestMapping(method = RequestMethod.PUT)。

(2)舉例:
  @RequestMapping(value = "/emp{id}", method = RequestMethod.PUT)
等價於
  @PutMapping("/emp{id}")

@RestController
@RequestMapping("/api")
public class EmpController {

    @PutMapping("/emp{id}")
    public Result updateEmp(@PathVariable(name = "id") Integer id, @RequestBody Emp emp) {
        return Result.ok();
    }
}

 

5、@DeleteMapping

(1)功能:
  用於處理 HTTP 的 DELETE 請求。
  本質是:@RequestMapping(method = RequestMethod.DELETE)。

(2)舉例:
  @RequestMapping(value = "/emp{id}", method = RequestMethod.DELETE)
等價於
  @DeleteMapping("/emp{id}")

@RestController
@RequestMapping("/api")
public class EmpController {

    @DeleteMapping("/emp{id}")
    public Result deleteById(@PathVariable(name = "id") Integer id) {
        return Result.ok();
    }
}

 

6、@PathVariable

(1)功能:
  用於將請求地址中的模板變量 綁定到 請求處理類的方法的 參數上。
  請求地址中 使用 {} 包裹模板變量名。
  請求處理方法中 使用 @PathVariable 來獲取該模板變量名。

(2)常用參數:
  name 給參數取別名,等同於 value
  value 給參數取個別名,等同於 name
  require 如果參數是非必須項,將其設為 false,默認為 true

(3)舉例:
  如下例,通過 @PathVariable 綁定模板變量。
  使用 name 屬性后,變量名可以自定義,可以不同於 模板變量名。
即兩種方式:
  @PathVariable(name="id") Integer id2
或者
  @PathVariable(Integer id)

@RestController
@RequestMapping("/api")
public class EmpController {

    @GetMapping("/emp/{id}")
    public Result selectOne(@PathVariable(name="id") Integer id2) {
        return Result.ok();
    }

}

 

7、@RequestBody

(1)功能:
  用於處理請求參數列表,將其映射到一個對象中。
  根據請求參數名 與 對象屬性名 進行匹配並綁定值(只有匹配成功才會綁定值)。
  請求參數通過 HttpMessageConverter 進行傳遞。

(2)舉例:
  如下例,會將請求參數列表 映射 到 emp 這個對象中。

@RestController
@RequestMapping("/api")
public class EmpController {

    @PostMapping("/emp")
    public Result createEmp(@RequestBody Emp emp) {
        return Result.ok();
    }

}

 

8、@ResponseBody

(1)功能:
  用於處理請求方法的返回值,將其寫入 HTTP 的響應中。
注:
  @RestController 內部包含了 @ResponseBody 和 @Controller,所以使用 @RestController 注解時,不需要再添加 @ResponseBody 注解。

(2)舉例:
  如下例,將 createEmp 返回值寫入 HTTP 響應中(一般為 JSON 數據)。

@Controller
@ResponseBody 
@RequestMapping("/api")
public class EmpController {

    @PostMapping("/emp")
    public Result createEmp(@RequestBody Emp emp) {
        return Result.ok();
    }

}

 

9、@RestControllerAdvice、@ControllerAdvice

(1)功能:
  可以用來處理全局異常、數據綁定、數據預處理。
  全局異常需要與 @ExceptionHandler 注解一起使用。
  數據綁定需要與 @ModelAttribute 注解一起使用。
  數據預處理需要與 @InitBinder 注解一起使用。
注:
  @RestControllerAdvice 注解包含了 @ControllerAdvice 與 @ResponseBody 注解。

全局異常處理:
  https://www.cnblogs.com/l-y-h/p/12781586.html#_label2
數據綁定、數據預處理:
  https://www.cnblogs.com/lenve/p/10748453.html

(2)舉例:
  如下例:通過 @RestControllerAdvice 注解標記一個全局異常處理類,
  當異常發生時,@ExceptionHandler 可以捕獲到相應的異常信息,從而進行處理。

@RestControllerAdvice
public class GlobalExceptionHandler {
    private Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 處理 Exception 異常
     * @param e 異常
     * @return 處理結果
     */
    @ExceptionHandler(Exception.class)
    public Result handlerException(Exception e) {
        logger.error(e.getMessage(), e);
        return Result.error().message("系統異常");
    }

    /**
     * 處理空指針異常
     * @param e 異常
     * @return 處理結果
     */
    @ExceptionHandler(NullPointerException.class)
    public Result handlerNullPointerException(NullPointerException e) {
        logger.error(e.getMessage(), e);
        return Result.error().message("空指針異常");
    }
}

 

10、@ExceptionHandler

(1)功能;
  用於標注 處理指定異常的方法,當異常發生時,Spring 捕獲異常並將異常傳遞給 @ExceptionHandler 注解標記的方法,從而進行處理。

(2)舉例:
  與上例代碼相同,此處不重復粘貼。

11、@RequestParam

(1)功能:
  用於將請求體中的數據 綁定到 請求處理類的方法的 參數上。
注:
  可以通過 @PathVariable 獲取請求地址上的參數。
  可用通過 @RequestParam 獲取請求體中的參數。

(2)常用參數:
  defaultValue 當參數為空時,可以設置一個默認值。
  其余參數與 @PathVariable 相同。

(3)舉例:
  如下例,訪問地址 http://localhost:8080/emp/selectOne/3?id2=2 時,
  @PathVariable   獲取到的就是 3
  @RequestParam   獲取到的就是 2

@RestController
@RequestMapping("/api")
public class EmpController {

    @GetMapping("/selectOne/{id}")
    public Result selectOne(@PathVariable Integer id, @RequestParam Integer id2) {
        return Result.ok();
    }

}

 

12、@Controller、@RestController

(1)功能:
  是 @Component 注解的一個延伸。
  用於標注 Spring MVC 的控制器,Spring 自動掃描並配置該注解標注的類。
注:
  @RestController 內部包含了 @ResponseBody 和 @Controller,所以使用 @RestController 注解時,不需要再添加 @ResponseBody 注解。

(2)舉例:
  上面的代碼中都有體現,此處不重復粘貼。

 

二、Spring Bean 注解

Spring 注解配置 Bean 參考地址:
  https://www.cnblogs.com/l-y-h/p/11342174.html

1、@ComponentScan

(1)功能:
  此注解 用於指定需要被 Spring 掃描到的類。
  通過 basePackages 或者 value 屬性指定 需要掃描的包路徑。

(2)舉例:
  如下例:為 SpringBoot 注解標記 @SpringBootApplication 的內容。

@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
      @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {
}

 

2、@Component、@Repository、@Service

(1)功能:
  @Component 用於標注一個普通的組件類,沒有明確業務的范圍,只是表示需要被 Spring 掃描並管理。

(2)@Component 功能延伸(明確業務范圍)
  @Controller 用於標注一個控制類(用於控制層組件)。
  @Service 用於標注一個業務處理類(用於業務層組件)。
  @Repository 用於標注一個數據持久類(用於數據持久層組件)。

(3)舉例:
  如下例,為 @Service 注解的內容。

@Component
public @interface Service {
   @AliasFor(annotation = Component.class)
   String value() default "";
}

 

3、@Bean

(1)功能:
  將所標注的類納入到 Spring 的 Bean 管理工廠中。

(2)常用屬性:
  initMethod                     用於指定初始化方法
  destroyMethod              用於指定銷毀方法

(3)舉例:
  如下例,將 TestBean 納入 Bean 管理工廠中,項目一啟動,會默認加載。

@SpringBootApplication
public class TestEasycodeApplication {

    public static void main(String[] args) {
        SpringApplication.run(TestEasycodeApplication.class, args);
    }

    @Bean(initMethod ="initBean", destroyMethod = "destoryBean")
    public TestBean testBean() {
        return new TestBean();
    }
}

class TestBean {
    public void initBean() {
        System.out.println("============ hello ==============");
    }
    public void destoryBean() {
        System.out.println("============ destory ============");
    }
}

 

 

4、@DependsOn

(1)功能:
  在 Spring IOC 初始化一個 Bean 前,先初始化其他的 Bean 對象。

(2)舉例:
  如下例,如果沒有 指定 @DependsOn 時,會按照順序從上而下初始化。
  但是指定后,會先初始化指定的 Bean。

@SpringBootApplication
public class TestEasycodeApplication {

    public static void main(String[] args) {
        SpringApplication.run(TestEasycodeApplication.class, args);
    }

    @Bean(value = {"testBean"}, initMethod ="initBean", destroyMethod = "destoryBean")
    @DependsOn(value = {"testDependsOn"})
    public TestBean testBean() {
        return new TestBean();
    }

    @Bean(value = {"testDependsOn"}, initMethod ="initBean", destroyMethod = "destoryBean")
    public TestDependsOn testDependsOn() {
        return new TestDependsOn();
    }
}

class TestBean {
    public void initBean() {
        System.out.println("============ Bean hello ==============");
    }
    public void destoryBean() {
        System.out.println("============ Bean destory ============");
    }
}

class TestDependsOn {
    public void initBean() {
        System.out.println("============ Depends On hello ==============");
    }
    public void destoryBean() {
        System.out.println("============ Depends On destory ============");
    }
}

 

 

5、@Scope

(1)功能:
  用來定義 @Component、@Bean 標記的類的作用范圍。

(2)常用范圍:
  singleton 單例模式,每次獲取的都是同一個對象
  prototype 原型模式,每次獲取的都是不同的對象

(3)舉例:
  如下例,Bean 指定為 單例模式,則 IOC 容器中只存在一個該類的對象,每次調用時,都是同一個對象。

@Bean(value = {"testBean"}, initMethod ="initBean", destroyMethod = "destoryBean")
@Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
public TestBean testBean() {
    return new TestBean();
}

 

6、@Autowired、@Qualifier

(1)功能:
  用於標記 Spring 將要解析和注入 的依賴項。
  簡單地理解:將 Spring 容器的對應的內容注入到此注解標記的位置。

(2)舉例:
  @Autowired 默認按照類型去匹配。
  若想按照名稱去匹配,則需要通過 @Qualifier 注解一起使用(常用於同一個類型存在多個 Bean 對象的情況)。

@Autowired
@Qualifier("computer")
private Computer computer;

 

三、JSR-250 注解

1、@Resource

(1)功能:

  其功能等同於 @Autowired,用來自動注入,但是其默認按照名稱去匹配。

(2)常用參數:
  name            指定 bean 名稱去匹配
  type             指定 bean 類型去匹配

(3)舉例:

import javax.annotation.Resource;

private Computer computer;

@Resource
private Phone phone;  //插入類型為Phone的對象

@Resource  //注入bean對象
public void setComputer(Computer computer) {
    this.computer = computer;
}

 

2、@PostConstruct、@PreDestroy

(1)功能:
  @PostConstruct 注解用來標記 Bean 的初始化方法。
  @PreDestroy 注解用來標記 Bean 的銷毀方法。
  類似於 @Bean 中的 initMethod、destoryMethod 屬性。

(2)舉例:

package com.test;
import javax.annotation.PostConstruct;
import org.springframework.stereotype.Component;

@Component
public class ExampleBean {
    public void execute() {
        System.out.println("執行execute處理方法1");
    }
 
    @PostConstruct //等價於<bean init-method="init">
    public void init() {
        System.out.println("初始化");
    }

    @PreDestroy  //等價於<bean destory-method="destory">
    public void destory() {
        System.out.println("釋放資源");
    }
}    

 

四、SpringBoot 注解

1、@SpringBootApplication

(1)功能:
  是一個快捷的配置注解,被該注解標記的類中,可以定義一個或多個 Bean,並觸發自動配置 Bean 和 掃描組件。
  其為 @ComponentScan、@EnableAutoConfiguration、@Configuration 的組合注解。

(2)舉例:
  如下例,為 SpringBoot 啟動類

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;


@SpringBootApplication
public class TestEasycodeApplication {

    public static void main(String[] args) {
        SpringApplication.run(TestEasycodeApplication.class, args);
    }
}

 

2、@Configuration

(1)功能:
  此注解用於定義配置類,可用於替換 xml 配置文件(作用等同於 xml 配置文件),該注解標記的內部可以包含一個或多個 @Bean 聲明的方法,並由 Spring 容器進行管理。

(2)舉例:
  如下例,Configuration 注解內部 是一個 Component 注解。

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Configuration {
   @AliasFor(annotation = Component.class)
   String value() default "";
   boolean proxyBeanMethods() default true;
}

 

3、@EnableAutoConfiguration

(1)功能:
  此注解用於通知 Spring,根據當前類路徑引入的 jar 依賴包,自動配置與這些依賴包相關的配置項。

(2)舉例:
  如下例,為 EnableAutoConfiguration 注解的內容。

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import(AutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {

   String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration";
   Class<?>[] exclude() default {};
   String[] excludeName() default {};
}

 

4、@Conditional 相關注解

(1)功能:
  @Conditional 注解可以根據一些自定義條件動態選擇是否加載 某個 Bean 到 Spring IOC 容器中去。

(2)常見注解:
@ConditionalOnClass 與 @ConditionalOnMissingClass:
  根據某些類作為判斷依據,從而決定是否執行某個操作。
  比如 @ConditionalOnClass, 當指定的 class 在類路徑上時,才去實例化一個 Bean 到容器中。

@ConditionalOnBean 與 @ConditionalOnMissingBean:
  根據某對象作為判斷依據,從而決定是否執行某個操作。
  比如 @ConditionalOnBean, 當指定的對象存在時,才去實例化一個 Bean 到容器中。

@ConditionalOnProperty:
  根據某個配置文件是否滿足配置項作為判斷依據,從而決定是否執行某個操作。

@ConditionalOnResource
  根據某個配置文件是否存在作為判斷依據,從而決定是否執行某個操作。

@ConditionalExpression
  根據表達式作為判斷依據,從而決定是否執行某個操作。
  比如:表達式為 true 時,才會實例化一個 Bean 到容器中。

(3)舉例:
  如下例,為 redis 的配置(Redis backed session configuration.)。

@Configuration(proxyBeanMethods = false)
@ConditionalOnClass({ RedisTemplate.class, RedisIndexedSessionRepository.class })
@ConditionalOnMissingBean(SessionRepository.class)
@ConditionalOnBean(RedisConnectionFactory.class)
@Conditional(ServletSessionCondition.class)
@EnableConfigurationProperties(RedisSessionProperties.class)
class RedisSessionConfiguration {

   @Bean
   @ConditionalOnMissingBean
   ConfigureRedisAction configureRedisAction(RedisSessionProperties redisSessionProperties) {
      switch (redisSessionProperties.getConfigureAction()) {
      case NOTIFY_KEYSPACE_EVENTS:
         return new ConfigureNotifyKeyspaceEventsAction();
      case NONE:
         return ConfigureRedisAction.NO_OP;
      }
      throw new IllegalStateException(
            "Unsupported redis configure action '" + redisSessionProperties.getConfigureAction() + "'.");
   }

   @Configuration
   public static class SpringBootRedisHttpSessionConfiguration extends RedisHttpSessionConfiguration {

      @Autowired
      public void customize(SessionProperties sessionProperties, RedisSessionProperties redisSessionProperties) {
         Duration timeout = sessionProperties.getTimeout();
         if (timeout != null) {
            setMaxInactiveIntervalInSeconds((int) timeout.getSeconds());
         }
         setRedisNamespace(redisSessionProperties.getNamespace());
         setFlushMode(redisSessionProperties.getFlushMode());
         setSaveMode(redisSessionProperties.getSaveMode());
         setCleanupCron(redisSessionProperties.getCleanupCron());
      }

   }

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM