【框架】Spring/Spring Boot 常用注解总结
创始人
2025-05-30 02:28:18
0

目录

  • 1. @SpringBootApplication
  • 2. Spring Bean 相关
    • @Autowired
    • @Component,@Repository,@Service, @Controller
    • @RestController
    • @Scope
    • @Configuration
  • 3. 处理常见的 HTTP 请求类型
    • GET 请求
    • POST 请求
    • PUT 请求
    • DELETE 请求
    • PATCH 请求
  • 4. 前后端传值
    • @PathVariable 和 @RequestParam
    • @RequestBody
  • 5. 读取配置信息
    • @Value(常用)
    • @ConfigurationProperties(常用)
    • @PropertySource(不常用)
  • 6. 参数校验
    • 一些常用的字段验证的注解
    • 验证请求体(RequestBody)
    • 验证请求参数(Path Variables 和 Request Parameters)
  • 7. 全局处理 Controller 层异常
    • 8. JPA 相关
    • 创建表
    • 创建主键
    • 设置字段类型
    • 指定不持久化特定字段
    • 声明大字段
    • 创建枚举类型的字段
    • 增加审计功能
    • 删除/修改数据
    • 关联关系
  • 9. 事务 @Transactional

1. @SpringBootApplication

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

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

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

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

  • @EnableAutoConfiguration:启用 SpringBoot 的自动配置机制
  • @ComponentScan: 扫描被@Component (@Repository,@Service,@Controller)注解的 bean,注解默认会扫描该类所在的包下所有的类。
  • @Configuration:允许在 Spring 上下文中注册额外的 bean 或导入其他配置类

2. Spring Bean 相关

@Autowired

自动导入对象到类中,被注入进的类同样要被 Spring 容器管理比如:Service 类注入到 Controller 类中。

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

@Component,@Repository,@Service, @Controller

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

  • @Component :通用的注解,可标注任意类为 Spring 组件。如果一个 Bean 不知道属于哪个层,可以使用@Component 注解标注。
  • @Repository : 对应持久层即 Dao 层,主要用于数据库相关操作。
  • @Service : 对应服务层,主要涉及一些复杂的逻辑,需要用到 Dao 层。
  • @Controller : 对应 Spring MVC 控制层,主要用于接受用户请求并调用 Service 层返回数据给前端页面。

@RestController

@RestController注解是==@Controller和@ResponseBody的合集==,表示这是个控制器 bean,并且是将函数的返回值直接填入 HTTP 响应体中,是 REST 风格的控制器。

单独使用 @Controller 不加 @ResponseBody的话一般是用在要返回一个视图的情况,这种情况属于比较传统的 Spring MVC 的应用,对应于前后端不分离的情况。@Controller +@ResponseBody 返回 JSON 或 XML 形式数据

@Scope

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

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

四种常见的 Spring Bean 的作用域:

  • singleton : 唯一 bean 实例,Spring 中的 bean 默认都是单例的。
  • prototype : 每次请求都会创建一个新的 bean 实例。
  • request : 每一次 HTTP 请求都会产生一个新的 bean,该 bean 仅在当前 HTTP request 内有效。
  • session : 每一个 HTTP Session 会产生一个新的 bean,该 bean 仅在当前 HTTP session 内有效。

@Configuration

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

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

3. 处理常见的 HTTP 请求类型

5 种常见的请求类型:

  • GET :请求从服务器获取特定资源。举个例子:GET /users(获取所有学生)
  • POST :在服务器上创建一个新的资源。举个例子:POST /users(创建学生)
  • PUT :更新服务器上的资源(客户端提供更新后的整个资源)。举个例子:PUT /users/12(更新编号为 12 的学生)
  • DELETE :从服务器删除特定的资源。举个例子:DELETE /users/12(删除编号为 12 的学生)
  • PATCH :更新服务器上的资源(客户端提供更改的属性,可以看做作是部分更新),使用的比较少,这里就不举例子了。

GET 请求

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

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

POST 请求

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

关于@RequestBody注解的使用,在下面的“前后端传值”这块会讲到。

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

PUT 请求

@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) {......
}

DELETE 请求

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

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

PATCH 请求

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

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

4. 前后端传值

@PathVariable 和 @RequestParam

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

举个简单的例子:

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

如果我们请求的 url 是:/klasses/123456/teachers?type=web

那么我们服务获取到的数据就是:klassId=123456,type=web

@RequestBody

用于读取 Request 请求(可能是 POST,PUT,DELETE,GET 请求)的 body 部分并且Content-Type 为 application/json 格式的数据,接收到数据之后会自动将数据绑定到 Java 对象上去。系统会使用HttpMessageConverter或者自定义的HttpMessageConverter将请求的 body 中的 json 字符串转换为 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 {@NotBlankprivate String userName;@NotBlankprivate String password;@NotBlankprivate String fullName;
}

我们发送 post 请求到这个接口,并且 body 携带 JSON 数据:

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

这样我们的后端就可以直接把 json 格式的数据映射到我们的 UserRegisterRequest 类上。

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

5. 读取配置信息

很多时候我们需要将一些常用的配置信息比如阿里云 oss、发送短信、微信认证的相关配置信息等等放到配置文件中。

@Value(常用)

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

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

@ConfigurationProperties(常用)

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

只要在 Bean 上添加上了这个注解,指定好配置文件的前缀,那么对应的配置文件数据就会自动填充到 Bean 中

比如在application.properties文件中有如下配置文件

config.username=jay.zhou
config.password=3333

那么按照如下注解配置,SpringBoot项目中使用@ConfigurationProperties的Bean,它的username与password就会被自动注入值了

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;@Component
@ConfigurationProperties(prefix = "config")
public class TestBean{private String username;private String password;
}

@PropertySource(不常用)

@PropertySource读取指定 properties 文件

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

6. 参数校验

数据的校验的重要性就不用说了,即使在前端对数据进行校验的情况下,我们还是要对传入后端的数据再进行一遍校验,避免用户绕过浏览器直接通过一些 HTTP 工具直接向后端请求一些违法数据

JSR(Java Specification Requests) 是一套 JavaBean 参数校验的标准,它定义了很多常用的校验注解,我们可以直接将这些注解加在我们 JavaBean 的属性上面,这样就可以在需要校验的时候进行校验了,非常方便!

使用时需要自己引入 spring-boot-starter-validation 依赖

所有的注解,推荐使用 JSR 注解,即javax.validation.constraints,而不是org.hibernate.validator.constraints

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

  • @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 被注释的元素必须是一个将来的日期

验证请求体(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);}
}

验证请求参数(Path Variables 和 Request Parameters)

不要忘记在类上加上 @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);}
}

7. 全局处理 Controller 层异常

相关注解:

  1. @ControllerAdvice :注解定义全局异常处理类
  2. @ExceptionHandler :注解声明异常处理方法
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {/*** 请求参数异常处理*/@ExceptionHandler(MethodArgumentNotValidException.class)public ResponseEntity handleMethodArgumentNotValidException(MethodArgumentNotValidException ex, HttpServletRequest request) {......}
}

8. JPA 相关

JPA是Java Persistence API的简称,中文名Java持久层API,是JDK 5.0注解或XML描述对象-关系表的映射关系,并将运行期的实体对象持久化到数据库中

创建表

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

@Table 设置表名

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

创建主键

@Id :声明一个字段为主键。

使用@Id声明之后,我们还需要定义主键的生成策略。我们可以使用 @GeneratedValue 指定主键生成策略,主键生成策略可以自己选择

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

设置字段类型

@Column 声明字段

示例:

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

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

指定不持久化特定字段

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

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

@Entity(name="USER")
public class User {......@Transientprivate String secrect; // not persistent because of @Transient}

声明大字段

@Lob:声明某个字段为大字段。

@Lob
private String content;

创建枚举类型的字段

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

数据库里面对应存储的是 MALE/FEMALE

增加审计功能

只要继承了 AbstractAuditBase的类都会默认加上下面四个字段

@Data
@AllArgsConstructor
@NoArgsConstructor
@MappedSuperclass
@EntityListeners(value = AuditingEntityListener.class)
public abstract class AbstractAuditBase {@CreatedDate@Column(updatable = false)@JsonIgnoreprivate Instant createdAt;@LastModifiedDate@JsonIgnoreprivate Instant updatedAt;@CreatedBy@Column(updatable = false)@JsonIgnoreprivate String createdBy;@LastModifiedBy@JsonIgnoreprivate String updatedBy;
}

我们对应的审计功能对应地配置类可能是下面这样的(Spring Security 项目):


@Configuration
@EnableJpaAuditing
public class AuditSecurityConfiguration {@BeanAuditorAware auditorAware() {return () -> Optional.ofNullable(SecurityContextHolder.getContext()).map(SecurityContext::getAuthentication).filter(Authentication::isAuthenticated).map(Authentication::getName);}
}

@EnableJpaAuditing:开启 JPA 审计功能

删除/修改数据

@Modifying 注解提示 JPA 该操作是修改操作,注意还要配合@Transactional注解使用

@Repository
public interface UserRepository extends JpaRepository {@Modifying@Transactional(rollbackFor = Exception.class)void deleteByUserName(String userName);
}

关联关系

@OneToOne 声明一对一关系
@OneToMany 声明一对多关系
@ManyToOne 声明多对一关系
@ManyToMany 声明多对多关系

9. 事务 @Transactional

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

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

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

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

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

相关内容

热门资讯

安卓系统的总体框架,架构与核心... 你有没有想过,你的手机里那个神奇的安卓系统,它到底是怎么运作的呢?今天,就让我带你一探究竟,揭开安卓...
谁的安卓系统好,谁家的安卓系统... 说到安卓系统,这可是个热门话题呢!你有没有想过,这么多安卓手机品牌,哪个的操作系统最让你心动?今天,...
安卓系统信付通,安全无忧的移动... 你知道吗?在安卓手机的世界里,有一个超级好用的支付工具,它就是信付通。今天,就让我带你来全方位了解一...
小米官方系统安卓包,深度解析与... 亲爱的数码爱好者们,你是否曾为手机系统而烦恼?市面上那么多手机品牌,各种操作系统让人眼花缭乱。今天,...
自制安卓手机双系统,自制安卓手... 你有没有想过,自己的手机可以同时运行两个操作系统呢?没错,就是那种安卓手机双系统!听起来是不是很酷?...
小米安卓系统怎么设置,科技前沿... 小米手机的用户们,是不是觉得安卓系统有点复杂,设置起来有点头疼呢?别担心,今天就来手把手教你如何轻松...
点歌系统支持安卓系统么,安卓用... 你有没有想过,在手机上点歌听歌,是不是也能像在KTV里那样随心所欲呢?现在,就让我来告诉你一个超级酷...
原版安卓系统刷机,解锁无限可能 你有没有想过,你的安卓手机其实可以焕然一新?没错,就是那种原汁原味的安卓系统,让你的手机重新找回当初...
欧尚改装安卓系统,打造智能驾驶... 你有没有想过,你的欧尚汽车其实也可以变身成为智能座驾呢?没错,就是那个你每天上下班的伙伴——欧尚,现...
安卓系统最新事件,揭秘最新重大... 你知道吗?最近安卓系统可是发生了一件超级大事件,简直让人兴奋得心跳加速!这不,我就迫不及待地来和你分...
早期电话手表安卓系统,安卓系统... 你有没有想过,小时候那些看似简单的玩具,现在竟然也能玩出花来?比如,早期的电话手表,那时候的功能可真...
安卓老系统手机游戏,安卓老系统... 你有没有发现,那些安卓老系统手机,虽然看起来有点古老,但它们在游戏界可是有着自己独特的魅力呢!想象那...
安卓系统重启还是开关,重启与开... 手机突然卡壳了,是不是又该给安卓系统来个重启大法了?别急,今天就来聊聊这个让人又爱又恨的“安卓系统重...
安卓系统刷入iso,轻松实现个... 你有没有想过,你的安卓手机其实可以像变形金刚一样,换上全新的“皮肤”?没错,就是刷入ISO系统!这可...
安卓机系统无法关机,探究原因与... 最近我的安卓手机怎么啦?总是关机不成功,真是让人头疼啊!这可怎么办呢?别急,让我来帮你分析找出解决这...
安卓什么系统广告最多,揭秘最新... 你有没有发现,每次打开安卓手机,广告就像无处不在的小精灵,跳来跳去,让人眼花缭乱?今天,就让我带你一...
禁止中国使用安卓系统,“安卓系... 你知道吗?最近互联网上掀起了一股热议,那就是关于中国是否应该禁止使用安卓系统的话题。这可不是闹着玩的...
如何分辨ios系统和安卓系统,... 你有没有想过,你的手机里装的是iOS系统还是安卓系统呢?这两种系统各有千秋,但分辨它们其实并不难。今...
如何查询安卓系统版本,安卓系统... 你有没有想过,你的安卓手机里隐藏着一个小秘密——那就是它的系统版本!知道这个秘密,不仅能让你更好地了...
lg电视系统和安卓系统比较,性... 你有没有发现,现在家里的电视已经不再是那个傻乎乎的“大盒子”了?它变得聪明起来,能和你互动,能上网,...