為什么要寫這篇文章?
最近看到網(wǎng)上有一篇關(guān)于 SpringBoot 常用注解的文章被轉(zhuǎn)載的比較多,我看了文章內(nèi)容之后屬實(shí)覺(jué)得質(zhì)量有點(diǎn)低,并且有點(diǎn)會(huì)誤導(dǎo)沒(méi)有太多實(shí)際使用經(jīng)驗(yàn)的人(這些人又占據(jù)了大多數(shù))。所以,自己索性花了大概 兩天時(shí)間簡(jiǎn)單總結(jié)一下了。
因?yàn)槲覀€(gè)人的能力和精力有限,如果有任何不對(duì)或者需要完善的地方,請(qǐng)幫忙指出!Guide 哥感激不盡!
1. @SpringBootApplication
這里先單獨(dú)拎出@SpringBootApplication 注解說(shuō)一下,雖然我們一般不會(huì)主動(dòng)去使用它。
Guide 哥:這個(gè)注解是 Spring Boot 項(xiàng)目的基石,創(chuàng)建 SpringBoot 項(xiàng)目之后會(huì)默認(rèn)在主類加上。
@SpringBootApplication
public 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),這三個(gè)注解的作用分別是:
-
@EnableAutoConfiguration:?jiǎn)⒂?SpringBoot 的自動(dòng)配置機(jī)制 -
@ComponentScan: 掃描被@Component(@Service,@Controller)注解的 bean,注解默認(rèn)會(huì)掃描該類所在的包下所有的類。 -
@Configuration:允許在 Spring 上下文中注冊(cè)額外的 bean 或?qū)肫渌渲妙?/li>
2. Spring Bean 相關(guān)
2.1. @Autowired
自動(dòng)導(dǎo)入對(duì)象到類中,被注入進(jìn)的類同樣要被 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 容器幫我們自動(dòng)裝配 bean。要想把類標(biāo)識(shí)成可用于 @Autowired 注解自動(dòng)裝配的 bean 的類,可以采用以下注解實(shí)現(xiàn):
-
@Component:通用的注解,可標(biāo)注任意類為Spring組件。如果一個(gè) Bean 不知道屬于哪個(gè)層,可以使用@Component注解標(biāo)注。 -
@Repository: 對(duì)應(yīng)持久層即 Dao 層,主要用于數(shù)據(jù)庫(kù)相關(guān)操作。 -
@Service: 對(duì)應(yīng)服務(wù)層,主要涉及一些復(fù)雜的邏輯,需要用到 Dao 層。 -
@Controller: 對(duì)應(yīng) Spring MVC 控制層,主要用于接受用戶請(qǐng)求并調(diào)用 Service 層返回?cái)?shù)據(jù)給前端頁(yè)面。
2.3. @RestController
@RestController注解是@Controller和@ResponseBody的合集,表示這是個(gè)控制器 bean,并且是將函數(shù)的返回值直 接填入 HTTP 響應(yīng)體中,是 REST 風(fēng)格的控制器。
Guide 哥:現(xiàn)在都是前后端分離,說(shuō)實(shí)話我已經(jīng)很久沒(méi)有用過(guò)@Controller。如果你的項(xiàng)目太老了的話,就當(dāng)我沒(méi)說(shuō)。
單獨(dú)使用 @Controller 不加 @ResponseBody的話一般使用在要返回一個(gè)視圖的情況,這種情況屬于比較傳統(tǒng)的 Spring MVC 的應(yīng)用,對(duì)應(yīng)于前后端不分離的情況。@Controller +@ResponseBody 返回 JSON 或 XML 形式數(shù)據(jù)
關(guān)于@RestController 和 @Controller的對(duì)比,請(qǐng)看這篇文章:@RestController vs @Controller。
2.4. @Scope
聲明 Spring Bean 的作用域,使用方法:
@Bean
@Scope("singleton")
public Person personSingleton() {
return new Person();
}
四種常見的 Spring Bean 的作用域:
- singleton : 唯一 bean 實(shí)例,Spring 中的 bean 默認(rèn)都是單例的。
- prototype : 每次請(qǐng)求都會(huì)創(chuàng)建一個(gè)新的 bean 實(shí)例。
- request : 每一次 HTTP 請(qǐng)求都會(huì)產(chǎn)生一個(gè)新的 bean,該 bean 僅在當(dāng)前 HTTP request 內(nèi)有效。
- session : 每一次 HTTP 請(qǐng)求都會(huì)產(chǎn)生一個(gè)新的 bean,該 bean 僅在當(dāng)前 HTTP session 內(nèi)有效。
2.5. @Configuration
一般用來(lái)聲明配置類,可以使用 @Component注解替代,不過(guò)使用@Configuration注解聲明配置類更加語(yǔ)義化。
@Configuration
public class AppConfig {
@Bean
public TransferService transferService() {
return new TransferServiceImpl();
}
}
3. 處理常見的 HTTP 請(qǐng)求類型
5 種常見的請(qǐng)求類型:
-
GET :請(qǐng)求從服務(wù)器獲取特定資源。舉個(gè)例子:
GET /users(獲取所有學(xué)生) -
POST :在服務(wù)器上創(chuàng)建一個(gè)新的資源。舉個(gè)例子:
POST /users(創(chuàng)建學(xué)生) -
PUT :更新服務(wù)器上的資源(客戶端提供更新后的整個(gè)資源)。舉個(gè)例子:
PUT /users/12(更新編號(hào)為 12 的學(xué)生) -
DELETE :從服務(wù)器刪除特定的資源。舉個(gè)例子:
DELETE /users/12(刪除編號(hào)為 12 的學(xué)生) - PATCH :更新服務(wù)器上的資源(客戶端提供更改的屬性,可以看做作是部分更新),使用的比較少,這里就不舉例子了。
3.1. GET 請(qǐng)求
@GetMapping("users") 等價(jià)于@RequestMapping(value="/users",method=RequestMethod.GET)
@GetMapping("/users")
public ResponseEntity<List<User>> getAllUsers() {
return userRepository.findAll();
}
3.2. POST 請(qǐng)求
@PostMapping("users") 等價(jià)于@RequestMapping(value="/users",method=RequestMethod.POST)
關(guān)于@RequestBody注解的使用,在下面的“前后端傳值”這塊會(huì)講到。
@PostMapping("/users")
public ResponseEntity<User> createUser(@Valid @RequestBody UserCreateRequest userCreateRequest) {
return userRespository.save(user);
}
3.3. PUT 請(qǐng)求
@PutMapping("/users/{userId}") 等價(jià)于@RequestMapping(value="/users/{userId}",method=RequestMethod.PUT)
@PutMapping("/users/{userId}")
public ResponseEntity<User> updateUser(@PathVariable(value = "userId") Long userId,
@Valid @RequestBody UserUpdateRequest userUpdateRequest) {
......
}
3.4. DELETE 請(qǐng)求
@DeleteMapping("/users/{userId}")等價(jià)于@RequestMapping(value="/users/{userId}",method=RequestMethod.DELETE)
@DeleteMapping("/users/{userId}")
public ResponseEntity deleteUser(@PathVariable(value = "userId") Long userId){
......
}
3.5. PATCH 請(qǐng)求
一般實(shí)際項(xiàng)目中,我們都是 PUT 不夠用了之后才用 PATCH 請(qǐng)求去更新數(shù)據(jù)。
@PatchMapping("/profile")
public ResponseEntity updateStudent(@RequestBody StudentUpdateRequest studentUpdateRequest) {
studentRepository.updateDetail(studentUpdateRequest);
return ResponseEntity.ok().build();
}
4. 前后端傳值
掌握前后端傳值的正確姿勢(shì),是你開始 CRUD 的第一步!
4.1. @PathVariable 和 @RequestParam
@PathVariable用于獲取路徑參數(shù),@RequestParam用于獲取查詢參數(shù)。
舉個(gè)簡(jiǎn)單的例子:
@GetMapping("/klasses/{klassId}/teachers")
public List<Teacher> getKlassRelatedTeachers(
@PathVariable("klassId") Long klassId,
@RequestParam(value = "type", required = false) String type ) {
...
}
如果我們請(qǐng)求的 url 是:/klasses/{123456}/teachers?type=web
那么我們服務(wù)獲取到的數(shù)據(jù)就是:klassId=123456,type=web。
4.2. @RequestBody
用于讀取 Request 請(qǐng)求(可能是 POST,PUT,DELETE,GET 請(qǐng)求)的 body 部分并且Content-Type 為 application/json 格式的數(shù)據(jù),接收到數(shù)據(jù)之后會(huì)自動(dòng)將數(shù)據(jù)綁定到 Java 對(duì)象上去。系統(tǒng)會(huì)使用HttpMessageConverter或者自定義的HttpMessageConverter將請(qǐng)求的 body 中的 json 字符串轉(zhuǎn)換為 java 對(duì)象。
我用一個(gè)簡(jiǎn)單的例子來(lái)給演示一下基本使用!
我們有一個(gè)注冊(cè)的接口:
@PostMapping("/sign-up")
public ResponseEntity signUp(@RequestBody @Valid UserRegisterRequest userRegisterRequest) {
userService.save(userRegisterRequest);
return ResponseEntity.ok().build();
}
UserRegisterRequest對(duì)象:
@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserRegisterRequest {
@NotBlank
private String userName;
@NotBlank
private String password;
@NotBlank
private String fullName;
}
我們發(fā)送 post 請(qǐng)求到這個(gè)接口,并且 body 攜帶 JSON 數(shù)據(jù):
{"userName":"coder","fullName":"shuangkou","password":"123456"}
這樣我們的后端就可以直接把 json 格式的數(shù)據(jù)映射到我們的 UserRegisterRequest 類上。

需要注意的是:一個(gè)請(qǐng)求方法只可以有一個(gè)
@RequestBody,但是可以有多個(gè)@RequestParam和@PathVariable。 如果你的方法必須要用兩個(gè) @RequestBody來(lái)接受數(shù)據(jù)的話,大概率是你的數(shù)據(jù)庫(kù)設(shè)計(jì)或者系統(tǒng)設(shè)計(jì)出問(wèn)題了!
5. 讀取配置信息
很多時(shí)候我們需要將一些常用的配置信息比如阿里云 oss、發(fā)送短信、微信認(rèn)證的相關(guān)配置信息等等放到配置文件中。
下面我們來(lái)看一下 Spring 為我們提供了哪些方式幫助我們從配置文件中讀取這些配置信息。
我們的數(shù)據(jù)源application.yml內(nèi)容如下::
wuhan2020: 2020年初武漢爆發(fā)了新型冠狀病毒,疫情嚴(yán)重,但是,我相信一切都會(huì)過(guò)去!武漢加油!中國(guó)加油!
my-profile:
name: Guide哥
email: koushuangbwcx@163.com
library:
location: 湖北武漢加油中國(guó)加油
books:
- name: 天才基本法
description: 二十二歲的林朝夕在父親確診阿爾茨海默病這天,得知自己暗戀多年的校園男神裴之即將出國(guó)深造的消息——對(duì)方考取的學(xué)校,恰是父親當(dāng)年為她放棄的那所。
- name: 時(shí)間的秩序
description: 為什么我們記得過(guò)去,而非未來(lái)?時(shí)間“流逝”意味著什么?是我們存在于時(shí)間之內(nèi),還是時(shí)間存在于我們之中?卡洛·羅韋利用詩(shī)意的文字,邀請(qǐng)我們思考這一亙古難題——時(shí)間的本質(zhì)。
- name: 了不起的我
description: 如何養(yǎng)成一個(gè)新習(xí)慣?如何讓心智變得更成熟?如何擁有高質(zhì)量的關(guān)系? 如何走出人生的艱難時(shí)刻?
5.1. @value(常用)
使用 @Value("${property}") 讀取比較簡(jiǎn)單的配置信息:
@Value("${wuhan2020}")
String wuhan2020;
5.2. @ConfigurationProperties(常用)
通過(guò)@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
......
}
更多內(nèi)容請(qǐng)查看我的這篇文章:《10 分鐘搞定 SpringBoot 如何優(yōu)雅讀取配置文件?》 。
6. 參數(shù)校驗(yàn)
數(shù)據(jù)的校驗(yàn)的重要性就不用說(shuō)了,即使在前端對(duì)數(shù)據(jù)進(jìn)行校驗(yàn)的情況下,我們還是要對(duì)傳入后端的數(shù)據(jù)再進(jìn)行一遍校驗(yàn),避免用戶繞過(guò)瀏覽器直接通過(guò)一些 HTTP 工具直接向后端請(qǐng)求一些違法數(shù)據(jù)。
JSR(Java Specification Requests) 是一套 JavaBean 參數(shù)校驗(yàn)的標(biāo)準(zhǔn),它定義了很多常用的校驗(yàn)注解,我們可以直接將這些注解加在我們 JavaBean 的屬性上面,這樣就可以在需要校驗(yàn)的時(shí)候進(jìn)行校驗(yàn)了,非常方便!
校驗(yàn)的時(shí)候我們實(shí)際用的是 Hibernate Validator 框架。Hibernate Validator 是 Hibernate 團(tuán)隊(duì)最初的數(shù)據(jù)校驗(yàn)框架,Hibernate Validator 4.x 是 Bean Validation 1.0(JSR 303)的參考實(shí)現(xiàn),Hibernate Validator 5.x 是 Bean Validation 1.1(JSR 349)的參考實(shí)現(xiàn),目前最新版的 Hibernate Validator 6.x 是 Bean Validation 2.0(JSR 380)的參考實(shí)現(xiàn)。
SpringBoot 項(xiàng)目的 spring-boot-starter-web 依賴中已經(jīng)有 hibernate-validator 包,不需要引用相關(guān)依賴。如下圖所示(通過(guò) idea 插件—Maven Helper 生成):

非 SpringBoot 項(xiàng)目需要自行引入相關(guān)依賴包,這里不多做講解,具體可以查看我的這篇文章:《如何在 Spring/Spring Boot 中做參數(shù)校驗(yàn)?你需要了解的都在這里!》。
需要注意的是: 所有的注解,推薦使用 JSR 注解,即
javax.validation.constraints,而不是org.hibernate.validator.constraints
6.1. 一些常用的字段驗(yàn)證的注解
-
@NotEmpty被注釋的字符串的不能為 null 也不能為空 -
@NotBlank被注釋的字符串非 null,并且必須包含一個(gè)非空白字符 -
@Null被注釋的元素必須為 null -
@NotNull被注釋的元素必須不為 null -
@AssertTrue被注釋的元素必須為 true -
@AssertFalse被注釋的元素必須為 false -
@Pattern(regex=,flag=)被注釋的元素必須符合指定的正則表達(dá)式 -
@Email被注釋的元素必須是 Email 格式。 -
@Min(value)被注釋的元素必須是一個(gè)數(shù)字,其值必須大于等于指定的最小值 -
@Max(value)被注釋的元素必須是一個(gè)數(shù)字,其值必須小于等于指定的最大值 -
@DecimalMin(value)被注釋的元素必須是一個(gè)數(shù)字,其值必須大于等于指定的最小值 -
@DecimalMax(value)被注釋的元素必須是一個(gè)數(shù)字,其值必須小于等于指定的最大值 -
@Size(max=, min=)被注釋的元素的大小必須在指定的范圍內(nèi) -
@Digits (integer, fraction)被注釋的元素必須是一個(gè)數(shù)字,其值必須在可接受的范圍內(nèi) -
@Past被注釋的元素必須是一個(gè)過(guò)去的日期 -
@Future被注釋的元素必須是一個(gè)將來(lái)的日期 - ......
6.2. 驗(yàn)證請(qǐng)求體(RequestBody)
@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;
}
我們?cè)谛枰?yàn)證的參數(shù)上加上了@Valid注解,如果驗(yàn)證失敗,它將拋出MethodArgumentNotValidException。
@RestController
@RequestMapping("/api")
public class PersonController {
@PostMapping("/person")
public ResponseEntity<Person> getPerson(@RequestBody @Valid Person person) {
return ResponseEntity.ok().body(person);
}
}
6.3. 驗(yàn)證請(qǐng)求參數(shù)(Path Variables 和 Request Parameters)
一定一定不要忘記在類上加上 Validated 注解了,這個(gè)參數(shù)可以告訴 Spring 去校驗(yàn)方法參數(shù)。
@RestController
@RequestMapping("/api")
@Validated
public class PersonController {
@GetMapping("/person/{id}")
public ResponseEntity<Integer> getPersonByID(@Valid @PathVariable("id") @Max(value = 5,message = "超過(guò) id 的范圍了") Integer id) {
return ResponseEntity.ok().body(id);
}
}
更多關(guān)于如何在 Spring 項(xiàng)目中進(jìn)行參數(shù)校驗(yàn)的內(nèi)容,請(qǐng)看《如何在 Spring/Spring Boot 中做參數(shù)校驗(yàn)?你需要了解的都在這里!》這篇文章。
7. 全局處理 Controller 層異常
介紹一下我們 Spring 項(xiàng)目必備的全局處理 Controller 層異常。
相關(guān)注解:
-
@ControllerAdvice:注解定義全局異常處理類 -
@ExceptionHandler:注解聲明異常處理方法
如何使用呢?拿我們?cè)诘?5 節(jié)參數(shù)校驗(yàn)這塊來(lái)舉例子。如果方法參數(shù)不對(duì)的話就會(huì)拋出MethodArgumentNotValidException,我們來(lái)處理這個(gè)異常。
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {
/**
* 請(qǐng)求參數(shù)異常處理
*/
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<?> handleMethodArgumentNotValidException(MethodArgumentNotValidException ex, HttpServletRequest request) {
......
}
}
更多關(guān)于 Spring Boot 異常處理的內(nèi)容,請(qǐng)看我的這兩篇文章:
8. JPA 相關(guān)
8.1. 創(chuàng)建表
@Entity聲明一個(gè)類對(duì)應(yīng)一個(gè)數(shù)據(jù)庫(kù)實(shí)體。
@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 :聲明一個(gè)字段為主鍵。
使用@Id聲明之后,我們還需要定義主鍵的生成策略。我們可以使用 @GeneratedValue 指定主鍵生成策略。
1.通過(guò) @GeneratedValue直接使用 JPA 內(nèi)置提供的四種主鍵生成策略來(lái)指定主鍵生成策略。
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
JPA 使用枚舉定義了 4 中常見的主鍵生成策略,如下:
Guide 哥:枚舉替代常量的一種用法
public enum GenerationType {
/**
* 使用一個(gè)特定的數(shù)據(jù)庫(kù)表格來(lái)保存主鍵
* 持久化引擎通過(guò)關(guān)系數(shù)據(jù)庫(kù)的一張?zhí)囟ǖ谋砀駚?lái)生成主鍵,
*/
TABLE,
/**
*在某些數(shù)據(jù)庫(kù)中,不支持主鍵自增長(zhǎng),比如Oracle、PostgreSQL其提供了一種叫做"序列(sequence)"的機(jī)制生成主鍵
*/
SEQUENCE,
/**
* 主鍵自增長(zhǎng)
*/
IDENTITY,
/**
*把主鍵生成策略交給持久化引擎(persistence engine),
*持久化引擎會(huì)根據(jù)數(shù)據(jù)庫(kù)在以上三種主鍵生成 策略中選擇其中一種
*/
AUTO
}
@GeneratedValue注解默認(rèn)使用的策略是GenerationType.AUTO
public @interface GeneratedValue {
GenerationType strategy() default AUTO;
String generator() default "";
}
一般使用 MySQL 數(shù)據(jù)庫(kù)的話,使用GenerationType.IDENTITY策略比較普遍一點(diǎn)(分布式系統(tǒng)的話需要另外考慮使用分布式 ID)。
2.通過(guò) @GenericGenerator聲明一個(gè)主鍵策略,然后 @GeneratedValue使用這個(gè)策略
@Id
@GeneratedValue(generator = "IdentityIdGenerator")
@GenericGenerator(name = "IdentityIdGenerator", strategy = "identity")
private Long id;
等價(jià)于:
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
jpa 提供的主鍵生成策略有如下幾種:
public class DefaultIdentifierGeneratorFactory
implements MutableIdentifierGeneratorFactory, Serializable, ServiceRegistryAwareService {
@SuppressWarnings("deprecation")
public DefaultIdentifierGeneratorFactory() {
register( "uuid2", UUIDGenerator.class );
register( "guid", GUIDGenerator.class ); // can be done with UUIDGenerator + strategy
register( "uuid", UUIDHexGenerator.class ); // "deprecated" for new use
register( "uuid.hex", UUIDHexGenerator.class ); // uuid.hex is deprecated
register( "assigned", Assigned.class );
register( "identity", IdentityGenerator.class );
register( "select", SelectGenerator.class );
register( "sequence", SequenceStyleGenerator.class );
register( "seqhilo", SequenceHiLoGenerator.class );
register( "increment", IncrementGenerator.class );
register( "foreign", ForeignGenerator.class );
register( "sequence-identity", SequenceIdentityGenerator.class );
register( "enhanced-sequence", SequenceStyleGenerator.class );
register( "enhanced-table", TableGenerator.class );
}
public void register(String strategy, Class generatorClass) {
LOG.debugf( "Registering IdentifierGenerator strategy [%s] -> [%s]", strategy, generatorClass.getName() );
final Class previous = generatorStrategyToClassNameMap.put( strategy, generatorClass );
if ( previous != null ) {
LOG.debugf( " - overriding [%s]", previous.getName() );
}
}
}
8.3. 設(shè)置字段類型
@Column 聲明字段。
示例:
設(shè)置屬性 userName 對(duì)應(yīng)的數(shù)據(jù)庫(kù)字段名為 user_name,長(zhǎng)度為 32,非空
@Column(name = "user_name", nullable = false, length=32)
private String userName;
設(shè)置字段類型并且加默認(rèn)值,這個(gè)還是挺常用的。
Column(columnDefinition = "tinyint(1) default 1")
private Boolean enabled;
8.4. 指定不持久化特定字段
@Transient :聲明不需要與數(shù)據(jù)庫(kù)映射的字段,在保存的時(shí)候不需要保存進(jìn)數(shù)據(jù)庫(kù) 。
如果我們想讓secrect 這個(gè)字段不被持久化,可以使用 @Transient關(guān)鍵字聲明。
Entity(name="USER")
public class User {
......
@Transient
private String secrect; // not persistent because of @Transient
}
除了 @Transient關(guān)鍵字聲明, 還可以采用下面幾種方法:
static String secrect; // not persistent because of static
final String secrect = “Satish”; // not persistent because of final
transient String secrect; // not persistent because of transient
一般使用注解的方式比較多。
8.5. 聲明大字段
@Lob:聲明某個(gè)字段為大字段。
@Lob
private String content;
更詳細(xì)的聲明:
@Lob
//指定 Lob 類型數(shù)據(jù)的獲取策略, FetchType.EAGER 表示非延遲 加載,而 FetchType. LAZY 表示延遲加載 ;
@Basic(fetch = FetchType.EAGER)
//columnDefinition 屬性指定數(shù)據(jù)表對(duì)應(yīng)的 Lob 字段類型
@Column(name = "content", columnDefinition = "LONGTEXT NOT NULL")
private String content;
8.6. 創(chuàng)建枚舉類型的字段
可以使用枚舉類型的字段,不過(guò)枚舉字段要用@Enumerated注解修飾。
public enum Gender {
MALE("男性"),
FEMALE("女性");
private String value;
Gender(String str){
value=str;
}
}
@Entity
@Table(name = "role")
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String description;
@Enumerated(EnumType.STRING)
private Gender gender;
省略getter/setter......
}
數(shù)據(jù)庫(kù)里面對(duì)應(yīng)存儲(chǔ)的是 MAIL/FEMAIL。
8.7. 增加審計(jì)功能
只要繼承了 AbstractAuditBase的類都會(huì)默認(rèn)加上下面四個(gè)字段。
@Data
@AllArgsConstructor
@NoArgsConstructor
@MappedSuperclass
@EntityListeners(value = AuditingEntityListener.class)
public abstract class AbstractAuditBase {
@CreatedDate
@Column(updatable = false)
@JsonIgnore
private Instant createdAt;
@LastModifiedDate
@JsonIgnore
private Instant updatedAt;
@CreatedBy
@Column(updatable = false)
@JsonIgnore
private String createdBy;
@LastModifiedBy
@JsonIgnore
private String updatedBy;
}
我們對(duì)應(yīng)的審計(jì)功能對(duì)應(yīng)地配置類可能是下面這樣的(Spring Security 項(xiàng)目):
@Configuration
@EnableJpaAuditing
public class AuditSecurityConfiguration {
@Bean
AuditorAware<String> auditorAware() {
return () -> Optional.ofNullable(SecurityContextHolder.getContext())
.map(SecurityContext::getAuthentication)
.filter(Authentication::isAuthenticated)
.map(Authentication::getName);
}
}
簡(jiǎn)單介紹一下上面設(shè)計(jì)到的一些注解:
@CreatedDate: 表示該字段為創(chuàng)建時(shí)間時(shí)間字段,在這個(gè)實(shí)體被 insert 的時(shí)候,會(huì)設(shè)置值-
@CreatedBy:表示該字段為創(chuàng)建人,在這個(gè)實(shí)體被 insert 的時(shí)候,會(huì)設(shè)置值@LastModifiedDate、@LastModifiedBy同理。
@EnableJpaAuditing:開啟 JPA 審計(jì)功能。
8.8. 刪除/修改數(shù)據(jù)
@Modifying 注解提示 JPA 該操作是修改操作,注意還要配合@Transactional注解使用。
@Repository
public interface UserRepository extends JpaRepository<User, Integer> {
@Modifying
@Transactional(rollbackFor = Exception.class)
void deleteByUserName(String userName);
}
8.9. 關(guān)聯(lián)關(guān)系
-
@OneToOne聲明一對(duì)一關(guān)系 -
@OneToMany聲明一對(duì)多關(guān)系 -
@ManyToOne聲明多對(duì)一關(guān)系 -
MangToMang聲明多對(duì)多關(guān)系
更多關(guān)于 Spring Boot JPA 的文章請(qǐng)看我的這篇文章:一文搞懂如何在 Spring Boot 正確中使用 JPA 。
9. 事務(wù) @Transactional
在要開啟事務(wù)的方法上使用@Transactional注解即可!
@Transactional(rollbackFor = Exception.class)
public void save() {
......
}
我們知道 Exception 分為運(yùn)行時(shí)異常 RuntimeException 和非運(yùn)行時(shí)異常。在@Transactional注解中如果不配置rollbackFor屬性,那么事物只會(huì)在遇到RuntimeException的時(shí)候才會(huì)回滾,加上rollbackFor=Exception.class,可以讓事物在遇到非運(yùn)行時(shí)異常時(shí)也回滾。
@Transactional 注解一般用在可以作用在類或者方法上。
-
作用于類:當(dāng)把
@Transactional 注解放在類上時(shí),表示所有該類的public 方法都配置相同的事務(wù)屬性信息。 -
作用于方法:當(dāng)類配置了
@Transactional,方法也配置了@Transactional,方法的事務(wù)會(huì)覆蓋類的事務(wù)配置信息。
更多關(guān)于關(guān)于 Spring 事務(wù)的內(nèi)容請(qǐng)查看:
10. json 數(shù)據(jù)處理
10.1. 過(guò)濾 json 數(shù)據(jù)
@JsonIgnoreProperties 作用在類上用于過(guò)濾掉特定字段不返回或者不解析。
//生成json時(shí)將userRoles屬性過(guò)濾
@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時(shí)將userRoles屬性過(guò)濾
@JsonIgnore
private List<UserRole> userRoles = new ArrayList<>();
}
10.2. 格式化 json 數(shù)據(jù)
@JsonFormat一般用來(lái)格式化 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. 扁平化對(duì)象
@Getter
@Setter
@ToString
public class Account {
@JsonUnwrapped
private Location location;
@JsonUnwrapped
private 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;
}
}
未扁平化之前:
{
"location": {
"provinceName":"湖北",
"countyName":"武漢"
},
"personInfo": {
"userName": "coder1234",
"fullName": "shaungkou"
}
}
使用@JsonUnwrapped 扁平對(duì)象之后:
@Getter
@Setter
@ToString
public class Account {
@JsonUnwrapped
private Location location;
@JsonUnwrapped
private PersonInfo personInfo;
......
}
{
"provinceName":"湖北",
"countyName":"武漢",
"userName": "coder1234",
"fullName": "shaungkou"
}
11. 測(cè)試相關(guān)
@ActiveProfiles一般作用于測(cè)試類上, 用于聲明生效的 Spring 配置文件。
@SpringBootTest(webEnvironment = RANDOM_PORT)
@ActiveProfiles("test")
@Slf4j
public abstract class TestBase {
......
}
@Test聲明一個(gè)方法為測(cè)試方法
@Transactional被聲明的測(cè)試方法的數(shù)據(jù)會(huì)回滾,避免污染測(cè)試數(shù)據(jù)。
@WithMockUser Spring Security 提供的,用來(lái)模擬一個(gè)真實(shí)用戶,并且可以賦予權(quán)限。
@Test
@Transactional
@WithMockUser(username = "user-id-18163138155", authorities = "ROLE_TEACHER")
void should_import_student_success() throws Exception {
......
}
作者:Snailclimb
鏈接:SpringBoot+Spring常用注解總結(jié)
來(lái)源:github