springboot常用注解

@SpringBootApplication

   这个注解是SpringBoot项目的基石,创建SpringBoot项目之后会默认在主类加上。

@SpringBootApplication
public class StudyApplication {
public static void main(String[] args) {
SpringApplication.run(StudyApplication.class, args);
}
}
可以把@SpringBootApplication看作是@Configuration、@EnableAutoConfiguration、@ComponentScan注解的集合。

根据SpringBoot官网,这三个注解的作用分别是:

@EnableAutoConfiguration:启用SpringBoot的自动配置机制。

@ComponentScan:扫描被@Component(@Service,@Controller)注解的bean,注解默认会扫描该类所在的包下所有的类。

@Configuration:允许在Spring上下文中注册额外的bean或导入其他配置类。

用于定义配置类,标注在类上,相当于把该类作为spring的xml配置文件中的,作用是用于配置spring容器(应用上下文)。

Spring Bean相关
2

@Autowired

    自动导入对象到类中,自动装配,其作用是为了消除代码里的getter/setter与bean属性中的property。

private UserService userService;
3

@Component,@Repository等

   我们一般使用@Autowired注解让Spring容器帮我们自动装配bean。要想把类标识成可用于@Autowired注解自动装配的bean的类,可以采用改一下注解实现:

@Component :通用的注解,可标注任意类为 Spring 组件。如果一个 Bean 不知道属于哪个层,可以使用@Component 注解标注。

@Repository : 对应持久层即 Dao 层,主要用于数据库相关操作。

@Service : 对应服务层,主要涉及一些复杂的逻辑,需要用到 Dao 层。

@Controller : 对应 Spring MVC 控制层,主要用户接受用户请求并调用 Service 层返回数据给前端页面。

4

@RestController

   现在都是前后端分离,一般都不用@Controller注解,而是使用@RestController注解。@RestController注解是@Controller和@ResponseBody的合集,表示这是个控制器 bean,并且是将函数的返回值直 接填入 HTTP 响应体中,是 REST 风格的控制器。

5

@Scope

    用在类上,声明Spring Bean的作用域,使用方法:

@Bean
@Scope(“singleton”)
public Person personSingleton(){
return new Person();
}
singleton : 唯一 bean 实例,Spring 中的 bean 默认都是单例的。

prototype : 每次请求都会创建一个新的 bean 实例。

request : 每一次 HTTP 请求都会产生一个新的 bean,该 bean 仅在当前 HTTP request 内有效。

session : 每一次 HTTP 请求都会产生一个新的 bean,该 bean 仅在当前 HTTP session 内有效。

6

@Configuration

一般用来声明配置类,可以使用@Component注解替代,不过使用@Configuration注解声明配置类更加语义化。

@Configuration
public class AppConfig{
@Bean
public TransferService transferService(){
return new TransferServiceImpl();
}
}
处理常见的HTTP请求类型
5种常见的请求类型:

GET :请求从服务器获取特定资源。例如:GET /users(获取所有学生)

POST :在服务器上创建一个新的资源。例如:POST /users(创建学生)

PUT :更新服务器上的资源(客户端提供更新后的整个资源)。例如:PUT /users/12(更新编号为 12 的学生)

DELETE :从服务器删除特定的资源。例如:DELETE /users/12(删除编号为 12 的学生)

PATCH :更新服务器上的资源(客户端提供更改的属性,可以看做作是部分更新),使用的比较少,这里就不举例子了。

7

Get请求-@GetMapping

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

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

Post请求-@PostMapping

@PostMapping(“users”) 等价于@RequestMapping(value="/users",method=RequestMethod.POST)

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

Put请求-@PutMapping

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

@PutMapping("/users/{userId}")
public ResponseEntity updateUser(@PathVariable(value=“userId”) Long userid,@Valid @RequestBody UserUpdateRequest userUpdateRequest){

}
10

Delete请求-@DeleteMapping

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

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

}
11

Patch请求-@PatchMapping

一般实际项目中,我们都是PUT不够用才使用PATCH请求去更新数据。

@PatchMapping("/profile")
public ResponseEntity updateUser(@RequestBody UserUpdateRequest userUpdateRequest){
userRepository.updateDetail(UserUpdateRequest);
return ResponseEntity.ok().build();
}
前后端传值
12

@PathVariable和@RequestParam

@PathVariable用于获取路径参数,@RequestParam用于获取查询参数。

@GetMapping("/user/{userId}/teachers")
public List getTeachers(
@PathVariable(“userId”) Long userId,
@RequestParam(value=“type”,required=false) String type){

}
例如:请求url是:/user/{12345}/teachers?type=web

那么我们服务获取到的数据为:userId=12345,type=web

13

@RequestBody

用于读取 Request 请求(可能是 POST,PUT,DELETE,GET 请求)的 body 部分并且Content-Type 为 application/json 格式的数据,接收到数据之后会自动将数据绑定到 Java 对象上去。系统会使用HttpMessageConverter或者自定义的HttpMessageConverter将请求的 body 中的 json 字符串转换为 java 对象。

需要注意的是:一个请求方法只可以有一个@RequestBody,但是可以有多个@RequestParam和@PathVariable。如果你的方法必须要用两个 @RequestBody来接受数据的话,大概率是你的数据库设计或者系统设计出问题了!

读取配置信息
14

@value(常用)

使用 @Value("${property}") 读取比较简单的配置信息:

15

@ConfigurationProperties(常用)

通过@ConfigurationProperties读取配置信息并与 bean 绑定。

参数校验
16

一些常用的字段验证的注解

@NotEmpty 被注释的字符串的不能为 null 也不能为空

@NotBlank 被注释的字符串非 null,并且必须包含一个非空白字符

@Null 被注释的元素必须为 null

@NotNull 被注释的元素必须不为 null

@AssertTrue 被注释的元素必须为 true

@AssertFalse 被注释的元素必须为 false

@Pattern(regex=,flag=)被注释的元素必须符合指定的正则表达式

@Email 被注释的元素必须是 Email 格式。

@Min(value)被注释的元素必须是一个数字,其值必须大于等于指定的最小值

@Max(value)被注释的元素必须是一个数字,其值必须小于等于指定的最大值

@DecimalMin(value)被注释的元素必须是一个数字,其值必须大于等于指定的最小值

@DecimalMax(value) 被注释的元素必须是一个数字,其值必须小于等于指定的最大值

@Size(max=, min=)被注释的元素的大小必须在指定的范围内

@Digits (integer, fraction)被注释的元素必须是一个数字,其值必须在可接受的范围内

@Past被注释的元素必须是一个过去的日期

@Future 被注释的元素必须是一个将来的日期

17

验证请求体(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;
}
我们在需要验证的参数上加上了@Valid注解,如果验证失败,它将抛出MethodArgumentNotValidException。

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

@PostMapping("/person")
public ResponseEntity getPerson(@RequestBody @Valid Person person) {
    return ResponseEntity.ok().body(person);
}

}
18

验证请求参数

@PathVariable和@RequestParameters,一定一定不要忘记在类上加上 Validated 注解了,这个参数可以告诉 Spring 去校验方法参数。

@RestController
@RequestMapping("/api")
@Validated
public class PersonController {

@GetMapping("/person/{id}")
public ResponseEntity getPersonByID(@Valid @PathVariable("id") @Max(value = 5,message = "超过 id 的范围了") Integer id) {
    return ResponseEntity.ok().body(id);
}

}
19

事务@Transactional

在要开启事务的方法上使用@Transactional注解即可!

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

}
我们知道 Exception 分为运行时异常 RuntimeException 和非运行时异常。在@Transactional注解中如果不配置rollbackFor属性,那么事物只会在遇到RuntimeException的时候才会回滚,加上rollbackFor=Exception.class,可以让事物在遇到非运行时异常时也回滚。

@Transactional 注解一般用在可以作用在类或者方法、接口上。

作用于类:当把@Transactional 注解放在类上时,表示所有该类的public 方法都配置相同的事务属性信息。

作用于方法:当类配置了@Transactional,方法也配置了@Transactional,方法的事务会覆盖类的事务配置信息。

作用于接口:不推荐这种使用方法,因为一旦标注在Interface上并且配置了Spring AOP 使用CGLib动态代理,将会导致@Transactional注解失效。

20

全局异常处理-@ControllerAdvice

包含@Component。可以被扫描到。统一处理异常。

21

全局异常处理-@ExceptionHandler

用在方法上面表示遇到这个异常就执行以下方法。

Json数据处理
22

过滤Json数据

@JsonIgnoreProperties作用在类上用于过滤掉特定字段不返回或者不解析。

//生成json时将userRoles属性过滤
@JsonIgnoreProperties({“userRoles”})
public class User {

private String userName;
private String fullName;
private String password;
@JsonIgnore
private List userRoles = new ArrayList<>();

}
@JsonIgnore一般用于类的属性上,作用和上面的@JsonIgnoreProperties 一样。

public class User {
private String userName;
private String fullName;
private String password;
//生成json时将userRoles属性过滤
@JsonIgnore
private List userRoles = new ArrayList<>();
}
23

格式化Json数据

@JsonFormat一般用来格式化json数据。

@JsonFormat(shape=JsonFormat.Shape.STRING, pattern=“yyyy-MM-dd’T’HH:mm:ss.SSS’Z’”, timezone=“GMT”)
private Date date;
JPA相关
24

创建表

@Entity声明一个类对应一个数据库实体。

@Table 设置表名

@Id声明一个字段为主键

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

设置字段类型

@Column 声明字段。

示例:

设置属性 userName 对应的数据库字段名为 user_name,长度为 32,非空

@Column(name = “user_name”, nullable = false, length=32)
private String userName;
设置字段类型并且加默认值,这个还是挺常用的。

@Column(columnDefinition = “tinyint(1) default 1”)
private Boolean enabled;
26

指定不持久化的特定字段

@Transient :声明不需要与数据库映射的字段,在保存的时候不需要保存进数据库 。

如果我们想让secrect 这个字段不被持久化,可以使用 @Transient关键字声明。

Entity(name=“USER”)
public class User {

@Transient
private String secrect; // not persistent because of @Transient
}
除了 @Transient关键字声明, 还可以采用下面几种方法:

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
27

创建枚举类型的字段

可以使用枚举类型的字段,不过枚举字段要用@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…
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值