Spring/Springboot 常用注解

整理一下常用的注解。

1. @SpringBootApplication

這里先單獨拎出@SpringBootApplication 注解說一下膛壹,雖然我們一般不會主動去使用它堰塌。
這個注解是 Spring Boot 項目的基石赵刑,創(chuàng)建 SpringBoot 項目之后會默認(rèn)在主類加上。

@SpringBootApplication
public class MasterApplication {
    public static void main(String[] args){
        SpringApplication.run(MasterApplication.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铐懊,注解默認(rèn)會掃描該類所在的包下所有的類。
  • @Configuration:允許在 Spring 上下文中注冊額外的 bean 或?qū)肫渌渲妙?/li>
2. Spring Bean 相關(guān)
2.1. @Autowired

自動導(dǎo)入對象到類中瞎疼,被注入進的類同樣要被 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。要想把類標(biāo)識成可用于 @Autowired 注解自動裝配的 bean 的類,可以采用以下注解實現(xiàn):

  • @Component :通用的注解贼急,可標(biāo)注任意類為 Spring 組件茅茂。如果一個 Bean 不知道屬于哪個層捏萍,可以使用這個注解標(biāo)注。
  • @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. @RestController

@RestController注解是@Controller@ResponseBody的合集,表示這是個控制器 bean,并且是將函數(shù)的返回值直 接填入 HTTP 響應(yīng)體中,是 REST 風(fēng)格的控制器。
單獨使用 @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 默認(rèn)都是單例的。
  • prototype : 每次請求都會創(chuàng)建一個新的 bean 實例芥挣。
  • request : 每一次 HTTP 請求都會產(chǎn)生一個新的 bean驱闷,該 bean 僅在當(dāng)前 HTTP request 內(nèi)有效。
  • session : 每一次 HTTP 請求都會產(chǎn)生一個新的 bean空免,該 bean 僅在當(dāng)前 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(獲取所有學(xué)生)
  • POST :在服務(wù)器上創(chuàng)建一個新的資源坝咐。舉個例子:POST /users(創(chuàng)建學(xué)生)
  • PUT :更新服務(wù)器上的資源(客戶端提供更新后的整個資源)循榆。舉個例子:PUT /users/12(更新編號為 12 的學(xué)生)
  • DELETE :從服務(wù)器刪除特定的資源。舉個例子:DELETE /users/12(刪除編號為 12 的學(xué)生)
  • PATCH :更新服務(wù)器上的資源(客戶端提供更改的屬性墨坚,可以看做作是部分更新)秧饮,使用的比較少,這里就不舉例子了框杜。
3.1. GET 請求

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

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

@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.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ù)振劳。

 @PatchMapping("/profile")
  public ResponseEntity updateStudent(@RequestBody StudentUpdateRequest studentUpdateRequest) {
        studentRepository.updateDetail(studentUpdateRequest);
        return ResponseEntity.ok().build();
  }
4. 前后端傳值

掌握前后端傳值的正確姿勢,是你開始 CRUD 的第一步油狂!

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 是:/classes/{123456}/teachers?type=web
那么我們服務(wù)獲取到的數(shù)據(jù)就是:classId=123456,type=web

4.2. @RequestBody

用于讀取 Request 請求(可能是 POST,PUT,DELETE,GET 請求)的 body 部分并且Content-Typeapplication/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類上。

image.png

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

5. 讀取配置信息

很多時候我們需要將一些常用的配置信息比如阿里云 oss鸳兽、發(fā)送短信、微信認(rèn)證的相關(guān)配置信息等等放到配置文件中罕拂。
下面我們來看一下 Spring 為我們提供了哪些方式幫助我們從配置文件中讀取這些配置信息揍异。
我們的數(shù)據(jù)源application.yml內(nèi)容如下:

appName: rw-order2
appId: 20200423001
my-profile:
  name: webxiaohua
  email: webxiaohua@163.com
library:
  location: 中國上海
  books:
    - name: 人類簡史
      description: 二十二歲的林朝夕在父親確診阿爾茨海默病這天,得知自己暗戀多年的校園男神裴之即將出國深造的消息——對方考取的學(xué)校爆班,恰是父親當(dāng)年為她放棄的那所衷掷。
    - name: 時間的秩序
      description: 為什么我們記得過去,而非未來蛋济?時間“流逝”意味著什么棍鳖?是我們存在于時間之內(nèi),還是時間存在于我們之中碗旅?卡洛·羅韋利用詩意的文字渡处,邀請我們思考這一亙古難題——時間的本質(zhì)。
    - name: 了不起的我
      description: 如何養(yǎng)成一個新習(xí)慣祟辟?如何讓心智變得更成熟医瘫?如何擁有高質(zhì)量的關(guān)系? 如何走出人生的艱難時刻旧困?
5.1. @value(常用)

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

@Value("${appName}")
String appName;
5.2. @ConfigurationProperties(常用)

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

@Component
@ConfigurationProperties(prefix = "library")
class LibraryProperties {
    @NotEmpty
    private String appName;
    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ù)校驗的標(biāo)準(zhǔn),它定義了很多常用的校驗注解陡蝇,我們可以直接將這些注解加在我們 JavaBean 的屬性上面痊臭,這樣就可以在需要校驗的時候進行校驗了哮肚,非常方便!

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)

一定一定不要忘記在類上加上 @Validated 注解了,這個參數(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);
    }
}
7. 全局處理 Controller 層異常

介紹一下我們 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 中常見的主鍵生成策略茉继,如下:
Guide 哥:枚舉替代常量的一種用法

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注解默認(rèn)使用的策略是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 提供的主鍵生成策略有如下幾種:

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 對應(yīng)的數(shù)據(jù)庫字段名為 user_name蜀备,長度為 32关摇,非空

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

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

Column(columnDefinition = "tinyint(1) default 1")
private Boolean enabled;
8.4. 指定不持久化特定字段

@Transient:聲明不需要與數(shù)據(jù)庫映射的字段输虱,在保存的時候不需要保存進數(shù)據(jù)庫 。
如果我們想讓secrect 這個字段不被持久化瓷蛙,可以使用 @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:聲明某個字段為大字段横堡。

@Lob
private String content;

更詳細的聲明:

@Lob
//指定 Lob 類型數(shù)據(jù)的獲取策略埋市, FetchType.EAGER 表示非延遲 加載,而 FetchType. LAZY 表示延遲加載 命贴;
@Basic(fetch = FetchType.EAGER)
//columnDefinition 屬性指定數(shù)據(jù)表對應(yīng)的 Lob 字段類型
@Column(name = "content", columnDefinition = "LONGTEXT NOT NULL")
private String content;
8.6. 創(chuàng)建枚舉類型的字段

可以使用枚舉類型的字段道宅,不過枚舉字段要用@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ù)庫里面對應(yīng)存儲的是 MAIL/FEMAIL胸蛛。

8.7. 增加審計功能

只要繼承了 AbstractAuditBase的類都會默認(rèn)加上下面四個字段污茵。

@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;
}

我們對應(yīng)的審計功能對應(yīng)地配置類可能是下面這樣的(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);
    }
}

簡單介紹一下上面設(shè)計到的一些注解:
@CreatedDate: 表示該字段為創(chuàng)建時間時間字段,在這個實體被 insert 的時候葬项,會設(shè)置值
@CreatedBy :表示該字段為創(chuàng)建人泞当,在這個實體被 insert 的時候,會設(shè)置值
@LastModifiedDate民珍、@LastModifiedBy同理襟士。
@EnableJpaAuditing:開啟 JPA 審計功能。

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 聲明一對一關(guān)系
@OneToMany 聲明一對多關(guān)系
@ManyToOne聲明多對一關(guān)系
MangToMang聲明多對多關(guān)系

9. 事務(wù) @Transactional

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

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

@Transactional(rollbackFor = Exception.class)
public void save() {
......
}
我們知道 Exception 分為運行時異常 RuntimeException 和非運行時異常陋桂。在@Transactional注解中如果不配置rollbackFor屬性,那么事物只會在遇到RuntimeException的時候才會回滾,加上rollbackFor=Exception.class,可以讓事物在遇到非運行時異常時也回滾。
@Transactional 注解一般用在可以作用在類或者方法上蝶溶。
作用于類:當(dāng)把@Transactional注解放在類上時嗜历,表示所有該類的public 方法都配置相同的事務(wù)屬性信息。
作用于方法:當(dāng)類配置了@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;
    @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 扁平對象之后:

@Getter
@Setter
@ToString
public class Account {
    @JsonUnwrapped
    private Location location;
    @JsonUnwrapped
    private PersonInfo personInfo;
    ......
}
{
  "provinceName":"湖北",
  "countyName":"武漢",
  "userName": "coder1234",
  "fullName": "shaungkou"
}
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é)到這里吧,以后慢慢補充!

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末后室,一起剝皮案震驚了整個濱河市缩膝,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌岸霹,老刑警劉巖疾层,帶你破解...
    沈念sama閱讀 219,039評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異贡避,居然都是意外死亡痛黎,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,426評論 3 395
  • 文/潘曉璐 我一進店門刮吧,熙熙樓的掌柜王于貴愁眉苦臉地迎上來湖饱,“玉大人,你說我怎么就攤上這事杀捻【幔” “怎么了?”我有些...
    開封第一講書人閱讀 165,417評論 0 356
  • 文/不壞的土叔 我叫張陵水醋,是天一觀的道長旗笔。 經(jīng)常有香客問我,道長拄踪,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,868評論 1 295
  • 正文 為了忘掉前任拳魁,我火速辦了婚禮惶桐,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘潘懊。我一直安慰自己姚糊,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,892評論 6 392
  • 文/花漫 我一把揭開白布授舟。 她就那樣靜靜地躺著救恨,像睡著了一般。 火紅的嫁衣襯著肌膚如雪释树。 梳的紋絲不亂的頭發(fā)上肠槽,一...
    開封第一講書人閱讀 51,692評論 1 305
  • 那天,我揣著相機與錄音奢啥,去河邊找鬼秸仙。 笑死,一個胖子當(dāng)著我的面吹牛桩盲,可吹牛的內(nèi)容都是我干的寂纪。 我是一名探鬼主播,決...
    沈念sama閱讀 40,416評論 3 419
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼捞蛋!你這毒婦竟也來了孝冒?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,326評論 0 276
  • 序言:老撾萬榮一對情侶失蹤拟杉,失蹤者是張志新(化名)和其女友劉穎庄涡,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體捣域,經(jīng)...
    沈念sama閱讀 45,782評論 1 316
  • 正文 獨居荒郊野嶺守林人離奇死亡啼染,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,957評論 3 337
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了焕梅。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片迹鹅。...
    茶點故事閱讀 40,102評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖贞言,靈堂內(nèi)的尸體忽然破棺而出斜棚,到底是詐尸還是另有隱情,我是刑警寧澤该窗,帶...
    沈念sama閱讀 35,790評論 5 346
  • 正文 年R本政府宣布弟蚀,位于F島的核電站,受9級特大地震影響酗失,放射性物質(zhì)發(fā)生泄漏义钉。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,442評論 3 331
  • 文/蒙蒙 一规肴、第九天 我趴在偏房一處隱蔽的房頂上張望捶闸。 院中可真熱鬧,春花似錦拖刃、人聲如沸删壮。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,996評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽央碟。三九已至,卻和暖如春均函,著一層夾襖步出監(jiān)牢的瞬間亿虽,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,113評論 1 272
  • 我被黑心中介騙來泰國打工边酒, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留经柴,地道東北人。 一個月前我還...
    沈念sama閱讀 48,332評論 3 373
  • 正文 我出身青樓墩朦,卻偏偏與公主長得像坯认,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,044評論 2 355

推薦閱讀更多精彩內(nèi)容