日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

Spring常见注解

發(fā)布時間:2025/4/16 66 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Spring常见注解 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

1.@SpringBootApplication

這里先單獨拎出 @SpringBootApplication 注解說一下,雖然我們一般不會主動去使用它。

這個注解是 Spring Boot 項目的基石,創(chuàng)建 SpringBoot 項目之后會默認在主類加上。

@SpringBootApplicationpublic class SpringSecurityJwtGuideApplication {public static void main(java.lang.String[] args) { SpringApplication.run(SpringSecurityJwtGuideApplication.class, args); }}

我們可以把 @SpringBootApplication 看作是 @Configuration@EnableAutoConfiguration 、 @ComponentScan 注解的集合。

package org.springframework.boot.autoconfigure; @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 {...... }package org.springframework.boot; @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Configuration public @interface SpringBootConfiguration {}

根據(jù) SpringBoot 官網(wǎng),這三個注解的作用分別是:

  • @EnableAutoConfiguration :啟用 SpringBoot 的自動配置機制
  • @ComponentScan : 掃描被 @Component ( @Service , @Controller )注解的 bean和掃描@Configuration標注的配置類,注解默認會掃描該類所在的包下所有的類。
  • @Configuration :允許在 Spring 上下文中注冊額外的 bean 或?qū)肫渌渲妙?/li>

2.Spring Bean相關(guān)

2.1@Autowired

自動導入對象到類中,被注入進的類同樣要被 Spring 容器管理比如:Service 類注入到 Controller 類中。

@Service public class UserService { ......}@RestController @RequestMapping("/users") public class UserController { @Autowired private UserService userService;...... }

2.2@Component,@Repository,@Service,@Controller

我們一般使用 @Autowired 注解讓 Spring 容器幫我們自動裝配 bean。要想把類標識成可用于@Autowired 注解自動裝配的 bean 的類,可以采用以下注解實現(xiàn):

  • @Component :通用的注解,可標注任意類為 Spring 組件。如果一個 Bean 不知道屬于哪個層,可以使用 @Component 注解標注。
  • @Repository : 對應(yīng)持久層即 Dao 層,主要用于數(shù)據(jù)庫相關(guān)操作。
  • @Service : 對應(yīng)服務(wù)層,主要涉及一些復(fù)雜的邏輯,需要用到 Dao 層。
  • @Controller : 對應(yīng) Spring MVC 控制層,主要用戶接受用戶請求并調(diào)用 Service 層返回數(shù)據(jù)給前端頁面。

2.3@RestCotroller

@RestController 注解是 @Controller和 @ ResponseBody 的合集,表示這是個控制器 bean,并且是將函數(shù)的返回值直接填入 HTTP 響應(yīng)體中,是 REST 風格的控制器。

現(xiàn)在都是前后端分離,項目中已經(jīng)很久沒有用過 @Controller 。

單獨使用 @Controller 不加 @ResponseBody 的話一般使用在要返回一個視圖的情況,這種情況屬于比較傳統(tǒng)的 Spring MVC 的應(yīng)用,對應(yīng)于前后端不分離的情況。 @Controller + @ResponseBody 返回JSON 或 XML 形式數(shù)據(jù)

2.4@Scope

聲明 Spring Bean 的作用域,使用方法:

@Bean @Scope("singleton") public Person personSingleton() {return new Person(); }

四種常見的 Spring Bean 的作用域:

  • singleton : 唯一 bean 實例,Spring 中的 bean 默認都是單例的。
  • prototype : 每次請求都會創(chuàng)建一個新的 bean 實例。
  • request : 每一次 HTTP 請求都會產(chǎn)生一個新的 bean,該 bean 僅在當前 HTTP request 內(nèi)有效。
  • session : 每一次 HTTP 請求都會產(chǎn)生一個新的 bean,該 bean 僅在當前 HTTP session 內(nèi)有效。

2.5@Configuration

一般用來聲明配置類,可以使用 @Component 注解替代,不過使用 Configuration 注解聲明配置類更加語義化。

@Configuration public class AppConfig {@Bean public TransferService transferService() {return new TransferServiceImpl(); } }

3.處理常見的HTTP請求類型

5 種常見的請求類型:

  • GET :請求從服務(wù)器獲取特定資源。舉個例子: GET /users (獲取所有學生)
  • POST :在服務(wù)器上創(chuàng)建一個新的資源。舉個例子: POST /users (創(chuàng)建學生)
  • PUT :更新服務(wù)器上的資源(客戶端提供更新后的整個資源)。舉個例子: PUT /users/12 (更新編號為 12 的學生)
  • DELETE :從服務(wù)器刪除特定的資源。舉個例子: DELETE /users/12 (刪除編號為 12 的學生)
  • PATCH :更新服務(wù)器上的資源(客戶端提供更改的屬性,可以看做作是部分更新),使用的比較少,這里就不舉例子了。

3.1GET請求

@GetMapping(“users”) 等價于 @RequestMapping(value="/users",method=RequestMethod.GET)

@GetMapping("/users") public ResponseEntity<List<User>> getAllUsers() { return userRepository.findAll(); }

3.2POST請求

@PostMapping(“users”) 等價于
@RequestMapping(value="/users",method=RequestMethod.POST)
關(guān)于 @RequestBody 注解的使用,在下面的“前后端傳值”這塊會講到。

@PostMapping("/users") public ResponseEntity<User> createUser(@Valid @RequestBody UserCreateRequest userCreateRequest) { return userRespository.save(user); }

3.3PUT請求

@PutMapping("/users/{userId}") 等價于
@RequestMapping(value="/users/{userId}",method=RequestMethod.PUT)

@PutMapping("/users/{userId}") public ResponseEntity<User> updateUser(@PathVariable(value = "userId") Long userId, @Valid @RequestBody UserUpdateRequest userUpdateRequest) {..... }

3.4DELETE請求

@DeleteMapping("/users/{userId}") 等價于
@RequestMapping(value="/users/{userId}",method=RequestMethod.DELETE)

@DeleteMapping("/users/{userId}") public ResponseEntity deleteUser(@PathVariable(value = "userId") Long userId){...... }

3.5PATCH請求

一般實際項目中,我們都是 PUT 不夠用了之后才用 PATCH 請求去更新數(shù)據(jù)。

@PatchMapping("/profile") public ResponseEntity updateStudent(@RequestBody StudentUpdateRequest studentUpdateRequest) { studentRepository.updateDetail(studentUpdateRequest);return ResponseEntity.ok().build(); }

4.前后端傳值

4.1@PathVariable和@RequestParam

@PathVariable 用于獲取路徑參數(shù), @RequestParam 用于獲取查詢參數(shù)。
舉個簡單的例子:

@GetMapping("/klasses/{klassId}/teachers") public List<Teacher> getKlassRelatedTeachers( @PathVariable("klassId") Long klassId, @RequestParam(value = "type", required = false) String type ) { ... }

如果我們請求的 url 是: /klasses/{123456}/teachers?type=web
那么我們服務(wù)獲取到的數(shù)據(jù)就是: klassId=123456,type=web 。

4.2@RequestBody

用于Request 請求(可能是 POST,PUT,DELETE,GET 請求)的 body 部分并且Content-Type 為application/json 格式的數(shù)據(jù),接收到數(shù)據(jù)之后會自動將數(shù)據(jù)綁定到 Java 對象上去。系統(tǒng)會使用HttpMessageConverter 或者自定義的 HttpMessageConverter 將請求的 body 中的 json 字符串轉(zhuǎn)換為 java 對象。

我用一個簡單的例子來給演示一下基本使用!
我們有一個注冊的接口:

@PostMapping("/sign-up") public ResponseEntity signUp(@RequestBody @Valid UserRegisterRequest userRegisterRequest) { userService.save(userRegisterRequest);return ResponseEntity.ok().build(); }

UserRegisterRequest 對象:

@Data @AllArgsConstructor @NoArgsConstructor public class UserRegisterRequest { @NotBlank private String userName; @NotBlank private String password; @FullName @NotBlank private String fullName; }

我們發(fā)送 post 請求到這個接口,并且 body 攜帶 JSON 數(shù)據(jù):

{"userName":"coder","fullName":"shuangkou","password":"123456"}

這樣我們的后端就可以直接把 json 格式的數(shù)據(jù)映射到我們的 UserRegisterRequest 類上。

  • 需要注意的是:一個請求方法只可以有一個 @RequestBody ,但是可以有多個 @RequestParam 和 @PathVariable 。 如果你的方法必須要用兩個 @RequestBody 來接受數(shù)據(jù)的話,大概率是你的數(shù)據(jù)庫設(shè)計或者系統(tǒng)設(shè)計出問題了!

5.讀取配置信息

很多時候我們需要將一些常用的配置信息比如阿里云 oss、發(fā)送短信、微信認證的相關(guān)配置信息等等放到配置文件中。

下面我們來看一下 Spring 為我們提供了哪些方式幫助我們從配置文件中讀取這些配置信息。

我們的數(shù)據(jù)源 application.yml 內(nèi)容如下:

wuhan2020: 2020年初武漢爆發(fā)了新型冠狀病毒,疫情嚴重,但是,我相信一切都會過去!武漢加油!中國 加油! my-profile:name: Guide哥 email: koushuangbwcx@163.com library:location: 湖北武漢加油中國加油books: -name: 天才基本法 -description: 二十二歲的林朝夕在父親確診阿爾茨海默病這天,得知自己暗戀多年的校園男神裴之 即將出國深造的消息——對方考取的學校,恰是父親當年為她放棄的那所。 -name: 時間的秩序

5.1@Value

使用 @Value("${property}") 讀取比較簡單的配置信息:

@Value("${wuhan2020}") String wuhan2020;

5.2@ConfigurationProperties

通過 @ConfigurationProperties 讀取配置信息并與 bean 綁定。

@Component @ConfigurationProperties(prefix = "library") class LibraryProperties { @NotEmpty private String location;private List<Book> books; @Setter @Getter @ToString static class Book { String name; String description; } 省略getter/setter ...... }

你可以像使用普通的 Spring bean 一樣,將其注入到類中使用。

5.3@PropertySource

@PropertySource 讀取指定 properties 文件

@Component @PropertySource("classpath:website.properties") class WebSite { @Value("${url}") private String url; 省略getter/setter ...... }

6.參數(shù)校驗

數(shù)據(jù)的校驗的重要性就不用說了,即使在前端對數(shù)據(jù)進行校驗的情況下,我們還是要對傳入后端的數(shù)據(jù)再進行一遍校驗,避免用戶繞過瀏覽器直接通過一些 HTTP 工具直接向后端請求一些違法數(shù)據(jù)。

JSR(Java Specification Requests) 是一套 JavaBean 參數(shù)校驗的標準,它定義了很多常用的校驗注解,我們可以直接將這些注解加在我們 JavaBean 的屬性上面,這樣就可以在需要校驗的時候進行校驗
了,非常方便!

校驗的時候我們實際用的是 Hibernate Validator 框架。Hibernate Validator 是 Hibernate 團隊最初的數(shù)據(jù)校驗框架,Hibernate Validator 4.x 是 Bean Validation 1.0(JSR 303)的參考實現(xiàn),HibernateValidator 5.x 是 Bean Validation 1.1(JSR 349)的參考實現(xiàn),目前最新版的Hibernate Validator 6.x是 Bean Validation 2.0(JSR 380)的參考實現(xiàn)。

SpringBoot 項目的 spring-boot-starter-web 依賴中已經(jīng)有 hibernate-validator 包,不需要引用相關(guān)依賴。如下圖所示(通過 idea 插件—Maven Helper 生成

需要注意的是: 所有的注解,推薦使用 JSR 注解,即 javax.validation.constraints ,而不 是 org.hibernate.validator.constraints

6.1一些常用字段驗證的注解

  • @NotEmpty 被注釋的字符串的不能為 null 也不能為空
  • @NotBlank 被注釋的字符串非 null,并且必須包含一個非空白字符
  • @Null 被注釋的元素必須為 null
  • @NotNull 被注釋的元素必須不為 null
  • @AssertTrue 被注釋的元素必須為 true
  • @AssertFalse 被注釋的元素必須為 false
  • @Pattern(regex=,flag=) 被注釋的元素必須符合指定的正則表達式
  • @Email 被注釋的元素必須是 Email 格式。
  • @Min(value) 被注釋的元素必須是一個數(shù)字,其值必須大于等于指定的最小值
  • @Max(value) 被注釋的元素必須是一個數(shù)字,其值必須小于等于指定的最大值
  • @DecimalMin(value) 被注釋的元素必須是一個數(shù)字,其值必須大于等于指定的最小值
  • @DecimalMax(value) 被注釋的元素必須是一個數(shù)字,其值必須小于等于指定的最大值
  • @Size(max=, min=) 被注釋的元素的大小必須在指定的范圍內(nèi)
  • @Digits (integer, fraction) 被注釋的元素必須是一個數(shù)字,其值必須在可接受的范圍內(nèi)
  • @Past 被注釋的元素必須是一個過去的日期
  • @Future 被注釋的元素必須是一個將來的日期

6.2驗證請求體(@RequestBody)

校驗類參數(shù)

@Data @AllArgsConstructor @NoArgsConstructor public class Person {@NotNull(message = "classId 不能為空")private String classId;@Size(max = 33) @NotNull(message = "name 不能為空") private String name; @Pattern(regexp = "((^Man$|^Woman$|^UGM$))", message = "sex 值不在可選范圍") @NotNull(message = "sex 不能為空") private String sex; @Email(message = "email 格式不正確") @NotNull(message = "email 不能為空") private String email; }

我們需要驗證的參數(shù)上加上了 @Valid 注解,如果驗證失敗,它將拋出MethodArgumentNotValidException 。

@RestController @RequestMapping("/api") public class PersonController { @PostMapping("/person") public ResponseEntity<Person> getPerson(@RequestBody @Valid Person person) { return ResponseEntity.ok().body(person);}}

6.3驗證請求參數(shù)(@PathVariable和@RequestParameters)

校驗方法參數(shù)

一定一定不要忘記在類上加上 Validated 注解了,這個參數(shù)可以告訴 Spring 去校驗方法參數(shù)

@RequestMapping("/api") @Validated public class PersonController { @GetMapping("/person/{id}") public ResponseEntity<Integer> getPersonByID(@Valid @PathVariable("id") @Max(value = 5,message = "超過 id 的范圍了") Integer id) { return ResponseEntity.ok().body(id);}}

7.全局處理相關(guān)

介紹一下我們 Spring 項目必備的全局處理 Controller 層異常。
相關(guān)注解:

  • @ControllerAdvice :注解定義全局異常處理類
  • @ExceptionHandler :注解聲明異常處理方法如何使用呢?拿我們在第 5 節(jié)參數(shù)校驗這塊來舉例子。如果方法參數(shù)不對的話就會拋出MethodArgumentNotValidException ,我們來處理這個異常。
  • @ControllerAdvice @ResponseBody public class GlobalExceptionHandler { /*** 請求參數(shù)異常處理 */ @ExceptionHandler(MethodArgumentNotValidException.class) public ResponseEntity<?> handleMethodArgumentNotValidException(MethodArgumentNotValidException ex, HttpServletRequest request) { ...... } }

    8.JPA相關(guān)

    8.1創(chuàng)建表

    @Entity 聲明一個類對應(yīng)一個數(shù)據(jù)庫實體。
    @Table 設(shè)置表明

    @Entity @Table(name = "role") public class Role { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id;private String name; private String description; 省略getter/setter...... }

    8.2創(chuàng)建主鍵

    @Id :聲明一個字段為主鍵。
    使用 @Id 聲明之后,我們還需要定義主鍵的生成策略。我們可以使用 @GeneratedValue 指定主鍵生成策略。

    1.通過 @GeneratedValue 直接使用 JPA 內(nèi)置提供的四種主鍵生成策略來指定主鍵生成策略。

    @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id;

    JPA 使用枚舉定義了 4 中常見的主鍵生成策略,如下:
    枚舉替代常量的一種用法

    public enum GenerationType { /*** 使用一個特定的數(shù)據(jù)庫表格來保存主鍵 * 持久化引擎通過關(guān)系數(shù)據(jù)庫的一張?zhí)囟ǖ谋砀駚砩芍麈I, * */ TABLE,/***在某些數(shù)據(jù)庫中,不支持主鍵自增長,比如Oracle、PostgreSQL其提供了一種叫做"序列 (sequence)"的機制生成主鍵 */ SEQUENCE,/*** 主鍵自增長 */ IDENTITY,/***把主鍵生成策略交給持久化引擎(persistence engine), *持久化引擎會根據(jù)數(shù)據(jù)庫在以上三種主鍵生成 策略中選擇其中一種 */ AUTO}

    @GeneratedValue 注解默認使用的策略是 GenerationType.AUTO

    public @interface GeneratedValue {GenerationType strategy() default AUTO;String generator() default ""; }

    一般使用 MySQL 數(shù)據(jù)庫的話,使用 GenerationType.IDENTITY 策略比較普遍一點(分布式系統(tǒng)的話需要另外考慮使用分布式 ID)。

    2.通過 @GenericGenerator 聲明一個主鍵策略,然后 @GeneratedValue 使用這個策略

    @Id @GeneratedValue(generator = "IdentityIdGenerator") @GenericGenerator(name = "IdentityIdGenerator", strategy = "identity") private Long id;

    等價于:

    @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id;

    jpa 提供的主鍵生成策略有如下幾種:

    8.3設(shè)置字段類型

    @Column 聲明字段。
    示例:

    設(shè)置屬性 userName 對應(yīng)的數(shù)據(jù)庫字段名為 user_name,長度為 32,非空

    @Column(name = "user_name", nullable = false, length=32) private String userName;

    設(shè)置字段類型并且加默認值,這個還是挺常用的。

    @Column(columnDefinition = "tinyint(1) default 1") private Boolean enabled;

    8.4指定不持久化特定字段

    8.5聲明大字段

    8.6創(chuàng)建枚舉類型的字段

    可以使用枚舉類型的字段,不過枚舉字段要用 @Enumerated 注解修飾。

    8.7增加審計功能


    8.8刪除、修改數(shù)據(jù)

    8.9關(guān)聯(lián)關(guān)系

    • @OneToOne 聲明一對一關(guān)系
    • @OneToMany 聲明一對多關(guān)系
    • @ManyToOne 聲明多對一關(guān)系
    • MangToMang 聲明多對多關(guān)系

    9.事務(wù)@Transaction

    在要開啟事務(wù)的方法上使用 @Transactional 注解即可!

    @Transactional(rollbackFor = Exception.class) public void save() { ...... }

    我們知道 Exception 分為運行時異常 RuntimeException 和非運行時異常。在 @Transactional 注解中如果不配置 rollbackFor 屬性,那么事物只會在遇到 RuntimeException 的時候才會回滾,加上rollbackFor=Exception.class ,可以讓事物在遇到非運行時異常時也回滾。

    @Transactional 注解一般用在可以作用在 類 或者 方法 上。

    • 作用于類:當把 @Transactional 注解放在類上時,表示所有該類的 public 方法都配置相同的事務(wù)屬性信息。
    • 作用于方法:當類配置了 @Transactional ,方法也配置了 @Transactional ,方法的事務(wù)會覆蓋類的事務(wù)配置信息

    10.json數(shù)據(jù)處理

    10.1過濾json數(shù)據(jù)

    @JsonIgnoreProperties 作用在類上用于過濾掉特定字段不返回或者不解析。

    //生成json時將userRoles屬性過濾 @JsonIgnoreProperties({"userRoles"}) public class User { private String userName; private String fullName; private String password; @JsonIgnore private List<UserRole> userRoles = new ArrayList<>();}

    @JsonIgnore 一般用于類的屬性上,作用和上面的@JsonIgnoreProperties 一樣。

    public class User { private String userName; private String fullName; private String password; //生成json時將userRoles屬性過濾 @JsonIgnore private List<UserRole> userRoles = new ArrayList<>(); }

    10.2格式化json數(shù)據(jù)

    @JsonFormat 一般用來格式化 json 數(shù)據(jù)。:
    比如:

    @JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", timezone="GMT") private Date date;

    10.3扁平化對象

    @Getter @Setter @ToString public class Account { @JsonUnwrapped private Location location; @JsonUnwrappedprivate PersonInfo personInfo; @Getter @Setter @ToString public static class Location { private String provinceName;private String countyName;}@Getter @Setter @ToString public static class PersonInfo { private String userName; private String fullName; }}

    未扁平化之前:

    使用@JsonUnwrapped 扁平對象之后:

    @Getter @Setter @ToString public class Account { @JsonUnwrapped private Location location; @JsonUnwrapped private PersonInfo personInfo; ...... }

    11.相關(guān)測試

    @ActiveProfiles 一般作用于測試類上, 用于聲明生效的 Spring 配置文件。

    @SpringBootTest(webEnvironment = RANDOM_PORT) @ActiveProfiles("test") @Slf4j public abstract class TestBase { ...... }

    @Test 聲明一個方法為測試方法
    @Transactional 被聲明的測試方法的數(shù)據(jù)會回滾,避免污染測試數(shù)據(jù)。
    @WithMockUser Spring Security 提供的,用來模擬一個真實用戶,并且可以賦予權(quán)限。

    @Test @Transactional @WithMockUser(username = "user-id-18163138155", authorities = "ROLE_TEACHER") void should_import_student_success() throws Exception {...... }

    總結(jié)

    以上是生活随笔為你收集整理的Spring常见注解的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。