在Spring和SpringBoot中,注解是一種非常重要的編程方式,它可以簡化代碼,提高開發(fā)效率。
一、核心注解
@SpringBootApplication是SpringBoot應用程序的核心注解,通常用于主類上。它包含了以下三個注解:
- @Configuration:表示該類是一個配置類,用于定義Spring的配置信息。允許在 Spring 上下文中注冊額外的 bean 或?qū)肫渌渲妙?/li>
- @EnableAutoConfiguration:表示啟用自動配置,SpringBoot會根據(jù)項目中的依賴自動配置相應的組件。
- @ComponentScan:表示啟用組件掃描,SpringBoot會自動掃描當前包及其子包下的所有組件。掃描被@Component (@Repository,@Service,@Controller)注解的 bean,注解默認會掃描該類所在的包下所有的類。
這個注解是 Spring Boot 項目的基石,創(chuàng)建 SpringBoot 項目之后會默認在主類加上。
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
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 {
......
}
注意事項:
- 主類應放在根包名下,以便能夠掃描到所有的組件。
- 如果需要自定義配置,可以在@SpringBootApplication注解中添加屬性,例如:exclude用于排除自動配置的類。
二、Spring Bean 相關
2.1 @Autowired
@Autowired是Spring的核心注解之一,用于實現(xiàn)依賴注入。它可以自動裝配Bean,無需手動創(chuàng)建和管理對象。被注入進的類同樣要被 Spring 容器管理比如:Service 類注入到 Controller 類中。
@RestController
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/users")
public List<User> getUsers() {
return userService.getUsers();
}
}
注意事項:
- 如果有多個實現(xiàn)類,可以使用@Qualifier注解指定Bean的名稱。
- 如果允許注入的Bean不存在,可以使用required屬性設置為false。
2.2 @Component, @Repository, @Service, @Controller
一般使用 @Autowired 注解讓 Spring 容器幫我們自動裝配 bean。要想把類標識成可用于 @Autowired 注解自動裝配的 bean 的類,可以采用以下注解實現(xiàn):
-
@Component
:通用的注解,可標注任意類為 Spring 組件。如果一個 Bean 不知道屬于哪個層,可以使用@Component 注解標注。 -
@Repository
:對應持久層即 Dao 層,主要用于數(shù)據(jù)庫相關操作。 -
@Service
:對應服務層,主要涉及一些復雜的邏輯,需要用到 Dao 層。 -
@Controller
:對應 Spring MVC 控制層,主要用于接受用戶請求并調(diào)用 Service 層返回數(shù)據(jù)給前端頁面。
2.3 @RestController 與 @Controller
@RestController注解是@Controller和@ResponseBody的合集,表示這是個控制器 bean,并且是將函數(shù)的返回值直接填入 HTTP 響應體中,是 REST 風格的控制器。其中,@ResponseBody:表示將方法返回值作為HTTP響應體,而不是視圖名稱。
在控制器類上添加@RestController注解,然后在方法上添加相應的HTTP請求映射注解,例如:@GetMapping、@PostMapping等。使用方法如下:
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello() {
return "Hello, SpringBoot!";
}
}
注意事項:
- 如果需要返回視圖,可以使用@Controller注解替換@RestController。
- 如果需要在方法上單獨使用@ResponseBody,可以將@RestController替換為@Controller。
@RestController 與 @Controller的區(qū)別:
- @Controller 返回一個頁面
單獨使用 @Controller 不加 @ResponseBody的話一般使用在要返回一個視圖的情況,這種情況屬于比較傳統(tǒng)的Spring MVC 的應用,對應于前后端不分離的情況。 - @RestController 返回JSON 或 XML 形式數(shù)據(jù)
@RestController只返回對象,對象數(shù)據(jù)直接以 JSON 或 XML 形式寫入 HTTP 響應(Response)中,這種情況屬于 RESTful Web服務,這也是目前日常開發(fā)所接觸的最常用的情況(前后端分離)。 - @Controller +@ResponseBody 返回JSON 或 XML 形式數(shù)據(jù)
如果需要在Spring4之前開發(fā) RESTful Web服務的話,需要使用@Controller 并結(jié)合@ResponseBody注解.也就是說@Controller +@ResponseBody = @RestController(Spring 4 之后新加的注解)。
2.4 @Configuration 與 @Component
@Configuration是Spring的核心注解之一,用于定義配置類。它表示該類是一個Java配置類,可以用來替代XML配置文件。其使用時是在類上添加@Configuration注解,然后在方法上添加@Bean注解定義Bean。
@Configuration
public class AppConfig {
@Bean
public UserService userService() {
return new UserService();
}
}
注意事項:
- 配置類通常與@ComponentScan、@EnableAutoConfiguration等注解一起使用。
- 如果需要導入其他配置類,可以使用@Import注解。
2.5 @Scope
@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 Session 會產(chǎn)生一個新的 bean,該 bean 僅在當前 HTTP session 內(nèi)有效。
三、處理常見的 HTTP 請求類型
幾種常見的請求類型如下:
-
GET
:請求從服務器獲取特定資源。舉個例子:GET /users(獲取所有用戶) -
POST
:在服務器上創(chuàng)建一個新的資源。舉個例子:POST /users(創(chuàng)建用戶) -
PUT
:更新服務器上的資源(客戶端提供更新后的整個資源)。舉個例子:PUT /users/1(更新編號為 1 的用戶) -
DELETE
:從服務器刪除特定的資源。舉個例子:DELETE /users/1(刪除編號為 1 的用戶) -
PATCH
:更新服務器上的資源(客戶端提供更改的屬性,可以看做作是部分更新),使用的比較少。
3.1 GET 請求
@GetMapping(“users”) 等價于@RequestMapping(value=“/users”,method=RequestMethod.GET)
@GetMapping("/users")
public ResponseEntity<List<User>> getAllUsers() {
return userRepository.findAll();
}
@GetMapping("/getUser/{userId}")
public ResponseEntity<User> getUser(@PathVariable(value = "userId") Long userId) {
return userRepository.find(userId);
}
3.2 POST 請求
@PostMapping(“users”) 等價于@RequestMapping(value=“/users”,method=RequestMethod.POST)關于@RequestBody注解的使用,在后面的“前后端傳值”會解釋。
@PostMapping("/users")
public ResponseEntity<User> createUser(@Valid @RequestBody UserCreateRequest userCreateRequest) {
return userRespository.save(userCreateRequest);
}
3.3 PUT 請求
@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.4 DELETE 請求
@DeleteMapping(“/users/{userId}”)等價于@RequestMapping(value=“/users/{userId}”,method=RequestMethod.DELETE)
@DeleteMapping("/users/{userId}")
public ResponseEntity deleteUser(@PathVariable(value = "userId") Long userId){
......
}
3.5 PATCH 請求
一般實際項目中,都是 PUT 不夠用了之后才用 PATCH 請求去更新數(shù)據(jù)。使用PUT請求時,會考慮將整個資源進行替換,適用于需要對整個資源進行更新或替換的情況。這可以確保資源的完整性和一致性。而當只需要對資源的部分屬性或字段進行更新時,可以選擇使用PATCH請求。PATCH請求更靈活,能夠?qū)崿F(xiàn)部分更新,同時避免了不必要的數(shù)據(jù)傳輸和處理,從而提高了效率。
@PatchMapping("/profile")
public ResponseEntity updateStudent(@RequestBody UserUpdateRequest userUpdateRequest) {
userRepository.updateDetail(userUpdateRequest);
return ResponseEntity.ok().build();
}
四、前后端傳值
4.1 @PathVariable 和 @RequestParam
@PathVariable用于獲取路徑參數(shù),@RequestParam用于獲取查詢參數(shù)。
@GetMapping("/user/{userId}")
public List<Teacher> getKlassRelatedTeachers(@PathVariable("userId") Long userId,
@RequestParam(value = "type", required = false) String type ) {
...
}
如果我們請求的 url 是:/user/123456?type=web,那么服務獲取到的數(shù)據(jù)就是:userId=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 {
private String userName;
private String password;
private String fullName;
}
發(fā)送 post 請求到這個接口,并且 body 攜帶 JSON 數(shù)據(jù):
{ "userName": "coder", "fullName": "shuangkou", "password": "123456" }
五、讀取配置信息
很多時候我們需要將一些常用的配置信息比如阿里云 oss、發(fā)送短信、微信認證的相關配置信息等等放到配置文件中。Spring 為我們提供了哪些方式幫助我們從配置文件中讀取這些配置信息。
數(shù)據(jù)源application.yml內(nèi)容如下:
myconfig: 我的配置
my-profile:
name: lt
email: lt@qq.com
library:
location: 位置
books:
- name: Java
description: Java語言。
- name: JavaScript
description: JavaScript語言。
5.1 @Value
使用 @Value(“${property}”) 讀取比較簡單的配置信息:
@Value("${myconfig}")
String myconfig;
5.2 @ConfigurationProperties
通過@ConfigurationProperties讀取配置信息并與 bean 綁定??梢韵袷褂闷胀ǖ?Spring bean 一樣,將其注入到類中使用。
@Component
@ConfigurationProperties(prefix = "library")
class LibraryProperties {
@NotEmpty
private String location;
private List<Book> books;
@Data
@ToString
static class Book {
String name;
String description;
}
......
}
5.3 @PropertySource
@PropertySource讀取指定 properties 文件
@Component
@PropertySource("classpath:website.properties")
class WebSite {
@Value("${url}")
private String url;
}
六、參數(shù)校驗
數(shù)據(jù)的校驗在前后端都需要,避免用戶繞過瀏覽器直接通過一些 HTTP 工具直接向后端請求一些違法數(shù)據(jù)。
JSR(Java Specification Requests)是一套 JavaBean 參數(shù)校驗的標準,它定義了很多常用的校驗注解,可以直接將這些注解加在我JavaBean 的屬性上面,這樣就可以在校驗的時候進行校驗了。校驗的時候?qū)嶋H用的是 Hibernate Validator 框架。Hibernate Validator 是 Hibernate 團隊最初的數(shù)據(jù)校驗框架,SpringBoot 項目的 spring-boot-starter-web( 2.3.11.RELEASE前的版本) 依賴中已經(jīng)有 hibernate-validator 包,不需要引用相關依賴;但是更新版本的 spring-boot-starter-web 依賴中不再有 hibernate-validator 包,需要自己引入 spring-boot-starter-validation 依賴。
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)
@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ù)(Path Variables 和 Request Parameters)
不要忘記在類上加上 @Valid 注解了,這個參數(shù)可以告訴 Spring 去校驗方法參數(shù)。
@RestController
@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);
}
}
七、全局處理 Controller 層異常
相關注解:
- @ControllerAdvice : 定義全局異常處理類
- @ExceptionHandler : 聲明異常處理方法
如果方法參數(shù)不對的話就會拋出MethodArgumentNotValidException,進而處理這個異常。
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {
//請求參數(shù)異常處理
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<?> handleMethodArgumentNotValidException(MethodArgumentNotValidException ex, HttpServletRequest request) {
......
}
}
八、Spring Data JPA 相關
Java Persistence API (JPA) 是一種基于 ORM (Object-Relational Mapping) 技術的 Java EE 規(guī)范。它主要用于將 Java 對象映射到關系型數(shù)據(jù)庫中,以便于對數(shù)據(jù)進行持久化操作。JPA詳解可以參考博文:Spring Data JPA 詳解
8.1 創(chuàng)建數(shù)據(jù)表
- @Entity 聲明一個類對應一個數(shù)據(jù)庫實體。
- @Table 設置表名
@Entity
@Table(name = "role")
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String description;
}
8.2 創(chuàng)建主鍵
- @Id:聲明一個字段為主鍵。
使用@Id聲明之后,我們還需要定義主鍵的生成策略。我們可以使用 @GeneratedValue 指定主鍵生成策略。
主鍵生成的兩種方法:
-
通過 @GeneratedValue直接使用 JPA 內(nèi)置提供的四種主鍵生成策略來指定主鍵生成策略。
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id;
JPA 使用枚舉定義了 4 種常見的主鍵生成策略,如下:
public enum GenerationType { // 使用一個特定的數(shù)據(jù)庫表格來保存主鍵,持久化引擎通過關系數(shù)據(jù)庫的一張?zhí)囟ǖ谋砀駚砩芍麈I TABLE, // 在某些數(shù)據(jù)庫中,不支持主鍵自增長,比如Oracle、PostgreSQL其提供了一種叫做"序列"的機制生成主鍵 SEQUENCE, // 主鍵自增長 IDENTITY, // 把主鍵生成策略交給持久化引擎,持久化引擎會根據(jù)數(shù)據(jù)庫在以上三種主鍵生成 策略中選擇其中一種 AUTO }
注意:@GeneratedValue注解默認使用的策略是GenerationType.AUTO。一般使用 MySQL 數(shù)據(jù)庫的話,使用GenerationType.IDENTITY策略比較普遍一點(分布式系統(tǒng)的話需要另外考慮使用分布式 ID)。
-
通過 @GenericGenerator聲明一個主鍵策略,然后 @GeneratedValue使用這個策略
@Id @GeneratedValue(generator = "IdentityIdGenerator") @GenericGenerator(name = "IdentityIdGenerator", strategy = "identity") private Long id;
等價于:
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id;
8.3 設置字段類型
- @Column 聲明字段。
示例:
-
設置屬性 userName 對應的數(shù)據(jù)庫字段名為 user_name,長度為 20,非空
@Column(name = "user_name", nullable = false, length=20) private String userName;
-
設置字段類型并且加默認值。
@Column(columnDefinition = "tinyint(1) default 0") private Boolean enabled;
8.4 指定不持久化特定字段
- @Transient:聲明不需要與數(shù)據(jù)庫映射的字段,在保存的時候不需要保存進數(shù)據(jù)庫 。
如果想讓secrect 這個字段不被持久化,可以使用 @Transient關鍵字聲明。
@Entity(name="USER")
public class User {
@Transient
private String secrect;
}
除了 @Transient關鍵字聲明, 還可以采用下面幾種方法:
static String secrect; // 由于靜態(tài)而不持久化
final String secrect = "Satish"; // 由于是final而不持久化
transient String secrect; // 由于瞬態(tài)而不持久化
8.5 聲明大字段
- @Lob:聲明某個字段為大字段。
大字段通常是指存儲較大數(shù)據(jù)量的字段,例如文本、二進制數(shù)據(jù)(如圖像或文件)、長字符串等。這些數(shù)據(jù)通常超過了數(shù)據(jù)庫表的普通列大小限制。
@Lob //聲明content為大字段
@Basic(fetch = FetchType.EAGER) //指定Lob類型數(shù)據(jù)的獲取策略, FetchType.EAGER為非延遲加載,F(xiàn)etchType.LAZY為延遲加載
@Column(name = "content", columnDefinition = "LONGTEXT NOT NULL") //columnDefinition 指定數(shù)據(jù)表對應的 Lob 字段類型
private String content;
8.6 創(chuàng)建枚舉類型的字段
- @Enumerated注解修飾枚舉字段。
聲明定義枚舉數(shù)據(jù):
public enum Gender {
MALE("男性"),
FEMALE("女性");
private String value;
Gender(String str){
value=str;
}
}
使用方法如下,數(shù)據(jù)庫里面對應存儲的是 MALE 或 FEMALE。
@Entity
@Table(name = "role")
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Enumerated(EnumType.STRING)
private Gender gender;
}
8.7 刪除 / 修改數(shù)據(jù)
- @Modifying 注解提示 JPA 該操作是修改操作,注意還要配合@Transactional注解使用。
@Repository
public interface UserRepository extends JpaRepository<User, Integer> {
@Modifying
@Transactional(rollbackFor = Exception.class)
void deleteByUserName(String userName);
}
8.8 增加審計功能
- @CreatedDate: 表示該字段為創(chuàng)建時間字段,在這個實體被 insert 的時候,會設置值
- @CreatedBy :表示該字段為創(chuàng)建人,在這個實體被 insert 的時候,會設置值
- @LastModifiedDate、@LastModifiedBy同理。
- @EnableJpaAuditing:開啟 JPA 審計功能。
只要繼承了 AbstractAuditBase的類都會默認加上下面四個字段:
@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;
}
對應的審計功能對應地配置類可能是下面這樣的(Spring Security 項目):
@Configuration
@EnableJpaAuditing
public class AuditSecurityConfiguration {
@Bean
AuditorAware<String> auditorAware() {
return () -> Optional.ofNullable(SecurityContextHolder.getContext())
.map(SecurityContext::getAuthentication)
.filter(Authentication::isAuthenticated)
.map(Authentication::getName);
}
}
8.9 聲明關聯(lián)關系
- @OneToOne 聲明一對一關系
- @OneToMany 聲明一對多關系
- @ManyToOne 聲明多對一關系
- @ManyToMany 聲明多對多關系
九、事務 @Transactional
- @Transactional 注解使用在要開啟事務的方法上,開啟該方法的事務
- @作用于類:Transactional 注解一般可以作用在類或者方法上。作用于類:
- 當把@Transactional 注解放在類上時,表示所有該類的 public 方法都配置相同的事務屬性信息。
- 作用于方法:當類配置了@Transactional,方法也配置了@Transactional,方法的事務會覆蓋類的事務配置信息。
作用于方法示例如下:
@Transactional(rollbackFor = Exception.class)
public void save() {
}
其中, Exception 分為運行時異常 RuntimeException 和非運行時異常。在@Transactional注解中如果不配置rollbackFor屬性,那么事務只會在遇到RuntimeException的時候才會回滾,加上rollbackFor=Exception.class,可以讓事務在遇到非運行時異常時也回滾。
十、JSON 數(shù)據(jù)處理
10.1 過濾 json 數(shù)據(jù)
- @JsonIgnoreProperties 作用在類上用于過濾掉特定字段不返回或者不解析。
//生成json時將userRoles屬性過濾 @JsonIgnoreProperties({"userRoles"}) public class User { private String userName; private String password; private List<UserRole> userRoles = new ArrayList<>(); }
- @JsonIgnore一般用于類的屬性上,作用和上面的@JsonIgnoreProperties 一樣。
public class User { private String userName; 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'", timezone="GMT")
private Date date;
10.3 扁平化對象
- @JsonUnwrapped 扁平化對象
@Data
@ToString
public class Account {
private Location location;
private PersonInfo personInfo;
@Data
@ToString
public static class Location {
private String provinceName;
}
@Data
@ToString
public static class PersonInfo {
private String userName;
}
}
未扁平化之前:
{
"location": {
"provinceName": "陜西",
},
"personInfo": {
"userName": "lt",
}
}
使用@JsonUnwrapped 扁平對象之后:
@Data
@ToString
public class Account {
@JsonUnwrapped
private Location location;
@JsonUnwrapped
private PersonInfo personInfo;
......
}
{
"provinceName": "陜西",
"userName": "lt",
}
十一、測試相關的注解
-
@ActiveProfiles 一般作用于測試類上, 用于聲明生效的 Spring 配置文件。
@SpringBootTest(webEnvironment = RANDOM_PORT) @ActiveProfiles("test") public abstract class TestBase { ...... }
-
@Test 聲明一個方法為測試方法
-
@Transactional 被聲明的測試方法的數(shù)據(jù)會回滾,避免污染測試數(shù)據(jù)。文章來源:http://www.zghlxwxcb.cn/news/detail-647199.html
-
@WithMockUser 由Spring Security 提供,用來模擬一個真實用戶,并且可以賦予權限。文章來源地址http://www.zghlxwxcb.cn/news/detail-647199.html
@Test @Transactional @WithMockUser(username = "lt", authorities = "ROLE_USER") void should_import_user_success() throws Exception { ...... }
到了這里,關于Spring&SpringBoot常用注解的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!