Spring&SpringBoot常用注解总结
1. @SpringBootApplication#
这里先单独拎出@SpringBootApplication
注解说一下,虽然我们一般不会主动去使用它。
@SpringBootApplication注解一般放在项目的一个启动类上,用来把启动类注入到容器中,用来定义容器扫描的范围,用来加载classpath环境中一些bean。
@SpringBootApplication
public class SpringSecurityJwtGuideApplication {
public static void main(java.lang.String[] args) {
SpringApplication.run(SpringSecurityJwtGuideApplication.class, args);
}
}
@SpringBootApplication注解主要包装了@SpringBootConfiguration、@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 {
}
根据 SpringBoot 官网,这三个注解的作用分别是:
-
@SpringBootConfiguration
主要用来把bean注入到容器中!因为该注解又封装了@Configuration注解。而@Configuration注解又封装了@Component注解,@Component注解主要用来把一个bean注入到容器中。因此,@SpringBootConfiguration注解就拥有了@Component注解的功能,用来把一个bean注入到容器中。 -
@EnableAutoConfiguration
:启用 SpringBoot 的自动配置机制。帮助SpringBoot应用将所有符合条件的@Configuration配置都加载到当前SpringBoot,并创建对应配置类的Bean,并把该Bean实体交给IoC容器进行管理。 -
@ComponentScan
: 扫描被@Component
(@Repository
,@Service
,@Controller
)注解的 bean,注解 默认 会扫描该类所在的包下所有的类。从定义扫描的路径中找出标识了需要装配的类,自动装配到spring的bean容器中
如下面图片,这里只设置读取ConfigService
类所在包的所有组件,但是最终输出也有mainConfig
,是因为该注解作用于MainConfig类,默认会扫描config包。
所以,包的路径扫描是多种设置累加的结果
2. Spring Bean 相关#
2.0 @Bean
#
简单来说,Bean 代指的就是那些被 IoC 容器所管理的对象。
我们需要告诉 IoC 容器帮助我们管理哪些对象,这个是通过配置元数据来定义的。配置元数据可以是 XML 文件、注解或者 Java 配置类。
下图简单地展示了 IoC 容器如何使用配置元数据来管理对象。
Spring帮助我们管理(装配)Bean分为两个部分
- 一个是注册Bean(@Component , @Repository , @ Controller , @Service , @Configuration)。
- 一个是装配Bean(@Autowired , @Resource,可以通过byTYPE(@Autowired)、byNAME(@Resource)的方式获取Bean)。
完成这两个动作有三种方式,一种是使用自动配置的方式、一种是使用JavaConfig的方式,一种就是使用XML配置的方式。
https://blog.csdn.net/qq_45470811/article/details/102903919
- @Component 自动装配。(作用就相当于 XML配置)
要想实现Bean的自动装配需要先认识Spring的两个核心组件:- 组件扫描(component scanning): Spring会自动的从应用上下文中发现创建的Bean。
- 自动装配(Autowring):装配各个Bean之间的依赖关系。
@Component
public class Student {
private String name = "lkm";
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
- @Bean 需要在Java配置类中使用,即类上需要加上@Configuration注解
@Configuration
public class WebSocketConfig {
@Bean
public Student student(){
return new StudentImpl();
}
}
两者都可以通过@Autowired装配
@Autowired
Student student;
- 上面的代码相当于下面的 xml 配置
<beans>
<bean id="student" class="com.xz.StudentImpl"/>
</beans>
@Component 和 @Bean 的区别是什么?#
两者的目的是一样的,都是注册bean到Spring容器中
区别:
-
@Component
注解作用于类,而@Bean
注解作用于方法。 -
@Component
@Component
注解表明一个类会作为组件类,并告知Spring要为这个类创建bean。通常用于自动检测以及类路径扫描自动装配bean到 Spring 容器中(我们可以使用@ComponentScan
注解定义要扫描的路径从中找出标识了需要装配的类自动装配到 Spring 的 bean 容器中)。注释类和bean之间存在隐式的一对一映射(即每个类一个bean)。
@Bean
注解告诉Spring这个方法将会返回一个对象,这个对象要注册为Spring应用上下文中的bean。通常方法体中包含了最终产生bean实例的逻辑。 -
@Bean
注解比@Component
注解的自定义性更强,而且很多地方我们只能通过@Bean
注解来注册 bean。比如当我们引用第三方库中的类需要装配到Spring
容器时,则只能通过@Bean
来实现。
那为什么有了@Compent,还需要@Bean呢?
如果你想要将第三方库中的组件装配到你的应用中,在这种情况下,是没有办法在它的类上添加@Component注解的,因此就不能使用自动化装配的方案了,但是我们可以使用@Bean,当然也可以使用XML配置。
下面这个例子是通过 @Component
无法实现的。(这个例子还得再理解)
@Bean
public OneService getService(status) {
case (status) {
when 1:
return new serviceImpl1();
when 2:
return new serviceImpl2();
when 3:
return new serviceImpl3();
}
}
2.1. @Autowired
#
自动导入对象到类中,被注入进的类同样要被 Spring 容器管理比如:Service 类注入到 Controller 类中。
@Service
public class UserService {
......
}
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserService userService;
......
}
步骤:@Autowird默认的注入方式为byType,也就是根据类型匹配;当有多个实现时,则通过byName注入,也可以通过配合@Qualifier注解来显式指定name值,指明要使用哪个具体的实现类
举例:
首先有一个接口UserService和两个实现类UserServiceImpl1和UserServiceImpl2,并且这两个实现类已经加入到Spring的IOC容器中了
@Service
public class UserServiceImpl1 implements UserService
@Service
public class UserServiceImpl2 implements UserService
错误示例:通过@Autowired注入使用
@Autowired
private UserService userService;
根据上面的步骤,可以很容易判断出,直接这么使用是会报错的
原因:首先通过byType注入,判断UserService类型有两个实现,无法确定具体是哪一个。于是通过byName方式,这里的变量名userService也无法匹配IOC容器中id(此处指的userServiceImpl1和userServiceImpl2),于是报错。
注意:通过注解注入到IOC容器的id值默认是其类名首字母小写
解决方案
方式一:
// 方式一:改变变量名
@Autowired
private UserService userServiceImpl1;
方式二:
// 方式二:配合@Qualifier注解来显式指定name值
@Autowired
@Qualifier(value = "userServiceImpl1")
private UserService userService;
2.2 @Resource
#
步骤:@Resource默认通过byName注入,如果没有匹配则通过byType注入
举例:
@Service
public class UserServiceImpl1 implements UserService
@Service
public class UserServiceImpl2 implements UserService
错误示例:
@Resource
private UserService userService;
首先通过byName匹配,变量名userService无法匹配IOC容器中任何一个id(这里指的userServiceImpl1和userServiceImpl2),于是通过byType匹配,发现类型UserService的实现类有两个,仍然无法确定,于是报错。
同时@Resource还有两个重要的属性:name和type,用来显式指定byName和byType方式注入
使用:对应4种情况
// 1. 默认方式:byName
@Resource
private UserService userDao;
// 2. 指定byName
@Resource(name="userService")
private UserService userService;
// 3. 指定byType
@Resource(type=UserService.class)
private UserService userService;
// 4. 指定byName和byType
@Resource(name="userService",type=UserService.class)
private UserService userService;
- 既没指定name属性,也没指定type属性:默认通过byName方式注入,如果byName匹配失败,则使用byType方式注入(也就是上面的那个例子)
- 指定name属性:通过byName方式注入,把变量名和IOC容器中的id去匹配,匹配失败则报错
- 指定type属性:通过byType方式注入,在IOC容器中匹配对应的类型,如果匹配不到或者匹配到多个则报错
- 同时指定name属性和type属性:在IOC容器中匹配,名字和类型同时匹配则成功,否则失败
@Autowired和@Resource注解的区别和联系#
联系#
- @Autowired和@Resource注解都是作为bean对象注入的时候使用的
- 两者都可以声明在字段和setter方法上
注意:如果声明在字段上,那么就不需要再写setter方法。但是本质上,该对象还是作为set方法的实参,通过执行set方法注入,只是省略了setter方法罢了
区别#
- @Autowired注解是Spring提供的,而@Resource注解是J2EE本身提供的
- @Autowird注解默认通过byType方式注入,而@Resource注解默认通过byName方式注入
- @Autowired注解注入的对象需要在IOC容器中存在,否则需要加上属性required=false,表示忽略当前要注入的bean,如果有直接注入,没有跳过,不会报错
对于byName和byType方式不太熟悉的可以看一下这里:Spring中的byName与byType
简单来说,byName就是变量名去匹配bean的id属性,而byType则是变量类型去匹配bean的class属性
<bean id="userService" class="com.test.UserServiceImpl"></bean>
@Autowired
private UserService userService;
此处byName就是拿变量名userService
去匹配IOC容器的id userService
,匹配成功;
而byType就是拿变量类型UserService
去匹配IOC容器的idcom.test.UserService.UserServiceImpl
,因为UserServiceImpl是UserService实现,所以也匹配成功
2.3. @Component
,@Repository
,@Service
, @Controller
#
我们一般使用 @Autowired
注解让 Spring 容器帮我们自动装配 bean。要想把类标识成可用于 @Autowired
注解自动装配的 bean 的类,可以采用以下注解实现:
@Component
:通用的注解,可标注任意类为Spring
组件。把普通POJO(Plain Ordinary Java Object简单的Java对象,实际就是普通JavaBeans)实例化到spring容器中,相当于配置文件中的<bean id="" class=""/>
。泛指各种组件,就是说当我们的类不属于各种归类的时候(不属于@Controller、@Services等的时候),我们就可以使用@Component来标注这个类。@Repository
: 对应持久层即 Dao 层,主要用于数据库相关操作。@Service
: 对应服务层,主要涉及一些复杂的逻辑,需要用到 Dao 层。@Controller
: 对应 Spring MVC 控制层,主要用于接受用户请求并调用 Service 层返回数据给前端页面。
@RestController
#
@RestController
注解是@Controller
和@ResponseBody
的合集,表示这是个控制器 bean,并且是将函数的返回值直接填入 HTTP 响应体中,是 REST 风格的控制器。@RestController
只返回对象,对象数据直接以 JSON 或 XML 形式写入 HTTP 响应(Response)中,这种情况属于 RESTful Web服务,这也是目前日常开发所接触的最常用的情况(前后端分离)。
Spring MVC 与 REST#
在传统的流程中,ModelAndView对象是从控制器转发到客户端的,通过在方法上加@ResponseBody,Spring直接从控制器返回数据,而不需要查找视图。
基于注解的MVC框架简化了创建RESTful web服务的过程。传统的Spring MVC控制器和RESTful web服务控制器之间的关键区别是HTTP响应体的创建方式。传统的MVC控制器依赖于视图技术,基于REST的web服务控制器仅返回对象,而对象数据直接以JSON/XML的形式写入HTTP响应。
REST(英文:Representational State Transfer,简称 REST)描述了一个架构样式的网络系统, 比如 web 应用程序。它并没有一个明确的标准,而更像是一种设计风格。核心价值在于如何设计出符合 REST 风格的网络接口。
- 资源(Resources)
网络上的一个实体,或者说是网络上的一个具体信息。它可以是一段文本、一张图片、一首歌曲、一种服务,总之就是一个具体的存在。可以用一个 URI(统一资源定位符)指向它,每种资源对应一个特定的 URI 。
要获取这个资源,访问它的 URI 就可以,因此 URI 即为每一个资源的独一无二的识别符。
- 表现层(Representation)
把资源具体呈现出来的形式,叫做它的表现层(Representation)。
比如,文本可以用 txt 格式表现,也可以用 HTML 格式、XML 格式、JSON 格式表现,甚至可以采用二进 制格式。
- 状态转化(State Transfer)
每发出一个请求,就代表了客户端和服务器的一次交互过程。
HTTP 协议,是一个无状态协议,即所有的状态都保存在服务器端。因此,如果客户端想要操作服务器, 必须通过某种手段,让服务器端发生“状态转化”(State Transfer)。
而这种转化是建立在表现层之上的,所以就是“表现层状态转化”。
具体说, 就是 HTTP 协议里面,四个表示操作方式的动词:GET、POST、PUT、DELETE。
它们分别对应四种基本操作:GET 用来获取资源,POST 用来新建资源,PUT 用来更新资源,DELETE 用来删除资源。
使用@Controller + @ResponseBody注解#
-
@Controller用于标记在一个类上,使用它标记的类就是一个Spring MVC Controller对象,分发处理器会扫描使用该注解的类的方法,并检测该方法是否使用了@RequestMapping注解。
-
@ResponseBody注解用于将@Controller的方法返回的对象,通过适当的HttpMessageConverter转换为指定格式后,写入到Response对象的body数据区,通常用来返回 JSON 或者 XML 数据,返回 JSON 数据的情况比较多。
@RestController
注解是@Controller
和@ResponseBody
的合集,表示这是个控制器 bean,并且是将函数的返回值直接填入 HTTP 响应体中,是 REST 风格的控制器。@RestController
只返回对象,对象数据直接以 JSON 或 XML 形式写入 HTTP 响应(Response)中,这种情况属于 RESTful Web服务,这也是目前日常开发所接触的最常用的情况(前后端分离)。
单独使用 @Controller
不加 @ResponseBody
的话一般是用在要返回一个视图的情况,这种情况属于比较传统的 Spring MVC 的应用,对应于前后端不分离的情况。@Controller
+@ResponseBody
返回 JSON 或 XML 形式数据
2.4 @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 内有效。
2.5. @Configuration
#
一般用来声明一个类为配置类,可以使用 @Component
注解替代,不过使用@Configuration
注解声明配置类更加语义化。
@Configuration
:声明一个类为配置类,用于取代bean.xml配置文件注册bean对象。
@Configuration注解常常一起搭配使用的注解有@Bean、@Scope、@Lazy三个比较常见:
- @Bean:等价于Spring中的bean标签用于注册bean对象的,内部有一些初始化、销毁的属性…
- @Scope:用于声明该bean的作用域,作用域有singleton、prototype、request、session。
- @Lazy:标记该bean是否开启懒加载。
@Configuration
public class AppConfig {
@Bean
public 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 :更新服务器上的资源(客户端提供更改的属性,可以看做作是部分更新),使用的比较少,这里就不举例子了。
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)
关于 @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 请求去更新数据。
@PatchMapping("/profile")
public ResponseEntity updateStudent(@RequestBody StudentUpdateRequest studentUpdateRequest) {
studentRepository.updateDetail(studentUpdateRequest);
return ResponseEntity.ok().build();
}
4. 前后端传值#
掌握前后端传值的正确姿势,是我开始 CRUD 的第一步!
4.1 @PathVariable
和 @RequestParam
#
@PathVariable
用于获取路径参数。
@PathVariable 映射 URL 绑定的占位符。通过 @PathVariable 可以将 URL 中占位符参数绑定到控制器处理方法的入参中:URL 中的 {xxx} 占位符可以通过@PathVariable(“xxx”) 绑定到操作方法的入参中。
1、若方法参数名称和需要绑定的url中变量名称一致时,可以简写:
@RequestMapping("/getUser/{name}")
public User getUser(@PathVariable String name){
return userService.selectUser(name);
}
2、若方法参数名称和需要绑定的url中变量名称不一致时,写成:
@RequestMapping("/getUserById/{name}")
public User getUser(@PathVariable("name") String userName){
return userService.selectUser(userName);
}
@RequestParam
用于获取查询参数
-
如果参数前写了@RequestParam(xxx),那么前端必须有对应的xxx名字才行(不管其是否有值,当然可以通过设置该注解的required属性来调节是否必须传),如果没有xxx名的话,那么请求会出错,报400。
-
如果参数前不写@RequestParam(xxx)的话,那么就前端可以有可以没有对应的xxx名字才行,如果有xxx名的话,那么就会自动匹配;没有的话,请求也能正确发送。
追注:这里与feign消费服务时不同;feign消费服务时,如果参数前什么也不写,那么会被默认是@RequestBody的。
举个简单的例子:
@GetMapping("/klasses/{klassId}/teachers")
public List<Teacher> getKlassRelatedTeachers(
@PathVariable("klassId") Long klassId,
@RequestParam(value = "type", required = false) String type ) {
...
}
}
如果我们请求的 url 是:/klasses/123456/teachers?type=web
那么我们服务获取到的数据就是:klassId=123456,type=web
。
4.2. @RequestBody
#
用于读取 Request 请求(可能是 POST,PUT,DELETE,GET 请求)的 body 部分并且Content-Type 为 application/json 格式的数据,接收到数据之后会(会使用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 {
@NotBlank
private String userName;
@NotBlank
private String password;
@NotBlank
private String fullName;
}
我们发送 post 请求到这个接口,并且 body 携带 JSON 数据:
{"userName":"coder","fullName":"shuangkou","password":"123456"}
这样我们的后端就可以直接把 json 格式的数据映射到我们的 UserRegisterRequest
类上。
👉 需要注意的是:一个请求方法只可以有一个@RequestBody
,但是可以有多个@RequestParam
和@PathVariable
。 如果你的方法必须要用两个 @RequestBody
来接受数据的话,大概率是你的数据库设计或者系统设计出问题了!
@RequestParam 和 @RequestBody#
-
一个请求,只有一个RequestBody;一个请求,可以有多个RequestParam。
-
当同时使用@RequestParam 和@RequestBody时,@RequestParam 定的参数可以是普通元素、数组、集合、对象等等(即:当@RequestBody 与@RequestParam同时使用时,原SpringMVC接收参数的机制不变,只不过RequestBody 接收的是请求体里面的数据;而RequestParam接收的是key-value里面的参数,所以它会被切面进行处理从而可以用普通元素、数组、集合、对象等接收)。
即:如果参数时放在请求体中,application/json传入后台的话,那么后台要用@RequestBody才能接收到;如果不是放在请求体中的话,那么后台接收前台传过来的参数时,要用@RequestParam来接收,或者形参前 什么也不写也能接收。
详细的例子可以看这里。
5. 读取配置信息#
很多时候我们需要将一些常用的配置信息比如阿里云 oss、发送短信、微信认证的相关配置信息等等放到配置文件中。
下面我们来看一下 Spring 为我们提供了哪些方式帮助我们从配置文件中读取这些配置信息。
我们的数据源application.yml
内容如下:
wuhan2020: 2020年初武汉爆发了新型冠状病毒,疫情严重,但是,我相信一切都会过去!武汉加油!中国加油!
my-profile:
name: Guide哥
email: koushuangbwcx@163.com
library:
location: 湖北武汉加油中国加油
books:
- name: 天才基本法
description: 二十二岁的林朝夕在父亲确诊阿尔茨海默病这天,得知自己暗恋多年的校园男神裴之即将出国深造的消息——对方考取的学校,恰是父亲当年为她放弃的那所。
- name: 时间的秩序
description: 为什么我们记得过去,而非未来?时间“流逝”意味着什么?是我们存在于时间之内,还是时间存在于我们之中?卡洛·罗韦利用诗意的文字,邀请我们思考这一亘古难题——时间的本质。
- name: 了不起的我
description: 如何养成一个新习惯?如何让心智变得更成熟?如何拥有高质量的关系? 如何走出人生的艰难时刻?
5.1. @Value
(常用)#
通过在properties文件中自定义一个属性,给这个属性赋值为有可能改变的值。使用 @Value("${property}")
读取比较简单的配置信息:
单独举例子
-
properties文件中自定义属性:
# 自定义一个属性,然后用哪个打开那个的属性即可 use.indicator.value = indicator_value # use.indicator.value = indicator_revise_value
-
代码中使用@Value()注解创建Bean对象:
@Value("${use.indicator.value}") private String userIndicatorValue;
-
然后再使用该对象即可.
System.out.println("userIndicatorValue" + userIndicatorValue);
-
输出结果:
需要注意的是@value
这种方式是不被推荐的,Spring 比较建议的是下面几种读取配置信息的方式。
5.2. @ConfigurationProperties
(常用)#
LibraryProperties
类上加了@Component
注解,我们可以像使用普通 bean 一样将其注入到类中使用。(开始的例子)
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
@ConfigurationProperties(prefix = "library")
@Setter
@Getter
@ToString
class LibraryProperties {
private String location;
private List<Book> books;
@Setter
@Getter
@ToString
static class Book {
String name;
String description;
}
}
这个时候你就可以像使用普通 bean 一样,将其注入到类中使用:
package cn.javaguide.readconfigproperties;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @author shuang.kou
*/
@SpringBootApplication
publicclass ReadConfigPropertiesApplication implements InitializingBean {
privatefinal LibraryProperties library;
public ReadConfigPropertiesApplication(LibraryProperties library) {
this.library = library;
}
public static void main(String[] args) {
SpringApplication.run(ReadConfigPropertiesApplication.class, args);
}
@Override
public void afterPropertiesSet() {
System.out.println(library.getLocation());
System.out.println(library.getBooks());
}
}
控制台输出:
湖北武汉加油中国加油
[LibraryProperties.Book(name=天才基本法, description........]
通过@ConfigurationProperties
读取并校验#
我们先将application.yml
修改为如下内容,明显看出这不是一个正确的 email 格式:
my-profile:
name: Guide哥
email: koushuangbwcx@
ProfileProperties
类没有加@Component
注解。我们在我们要使用ProfileProperties
的地方使用@EnableConfigurationProperties
注册我们的配置 bean:
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotEmpty;
/**
* @author shuang.kou
*/
@Getter
@Setter
@ToString
@ConfigurationProperties("my-profile")
@Validated
public class ProfileProperties {
@NotEmpty
private String name;
@Email
@NotEmpty
private String email;
//配置文件中没有读取到的话就用默认值
private Boolean handsome = Boolean.TRUE;
}
具体使用:
package cn.javaguide.readconfigproperties;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
/**
* @author shuang.kou
*/
@SpringBootApplication
@EnableConfigurationProperties(ProfileProperties.class)
publicclass ReadConfigPropertiesApplication implements InitializingBean {
privatefinal ProfileProperties profileProperties;
public ReadConfigPropertiesApplication(ProfileProperties profileProperties) {
this.profileProperties = profileProperties;
}
public static void main(String[] args) {
SpringApplication.run(ReadConfigPropertiesApplication.class, args);
}
@Override
public void afterPropertiesSet() {
System.out.println(profileProperties.toString());
}
}
因为我们的邮箱格式不正确,所以程序运行的时候就报错,根本运行不起来,保证了数据类型的安全性:
Binding to target org.springframework.boot.context.properties.bind.BindException: Failed to bind properties under 'my-profile' to cn.javaguide.readconfigproperties.ProfileProperties failed:
Property: my-profile.email
Value: koushuangbwcx@
Origin: class path resource [application.yml]:5:10
Reason: must be a well-formed email address
我们把邮箱测试改为正确的之后再运行,控制台就能成功打印出读取到的信息:
ProfileProperties(name=Guide哥, email=koushuangbwcx@163.com, handsome=true)
5.3. @PropertySource
(不常用)#
@PropertySource
读取指定 properties 文件
@Component
@PropertySource("classpath:website.properties")
class WebSite {
@Value("${url}")
private String url;
省略getter/setter
......
}
使用:
@Autowired
private WebSite webSite;
System.out.println(webSite.getUrl());//https://javaguide.cn/
6. 参数校验#
数据的校验的重要性就不用说了,即使在前端对数据进行校验的情况下,我们还是要对传入后端的数据再进行一遍校验,避免用户绕过浏览器直接通过一些 HTTP 工具直接向后端请求一些违法数据。
JSR(Java Specification Requests) 是一套 JavaBean 参数校验的标准,它定义了很多常用的校验注解,我们可以直接将这些注解加在我们 JavaBean 的属性上面,这样就可以在需要校验的时候进行校验了,非常方便!
校验的时候我们实际用的是 Hibernate Validator 框架。SpringBoot 项目的 spring-boot-starter-web 依赖中已经有 hibernate-validator 包,不需要引用相关依赖。
注:更新版本的 spring-boot-starter-web 依赖中不再有 hibernate-validator 包(如2.3.11.RELEASE),需要自己引入
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)
被注释的元素必须是一个数字,其值必须大于等于指定的最小值@Max(value)
被注释的元素必须是一个数字,其值必须小于等于指定的最大值@DecimalMin(value)
被注释的元素必须是一个数字,其值必须大于等于指定的最小值@DecimalMax(value)
被注释的元素必须是一个数字,其值必须小于等于指定的最大值@Size(max=, min=)
被注释的元素的大小必须在指定的范围内@Digits(integer, fraction)
被注释的元素必须是一个数字,其值必须在可接受的范围内@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;
}
正则表达式说明:
- ^string : 匹配以 string 开头的字符串 - string$ :匹配以 string 结尾的字符串 - ^string$ :精确匹配 string 字符串 - ((^Man$|^Woman$|^UGM$)) : 值只能在 Man,Woman,UGM 这三个值中选择
我们在需要验证的参数上加上了@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. 验证请求参数(@PathVariable 和 @RequestParam)#
一定一定不要忘记在类上加上 @Validated
注解了,这个参数可以告诉 Spring 去校验方法参数。
@RestController
@RequestMapping("/api")
@Validated
publicclass PersonController {
@GetMapping("/person/{id}")
public ResponseEntity<Integer> getPersonByID(@Valid @PathVariable("id") @Max(value = 5,message = "超过 id 的范围了") Integer id) {
return ResponseEntity.ok().body(id);
}
@PutMapping("/person")
public ResponseEntity<String> getPersonByName(@Valid @RequestParam("name") @Size(max = 6,message = "超过 name 的范围了") String name) {
return ResponseEntity.ok().body(name);
}
}
更多关于如何在 Spring 项目中进行参数校验的内容,请看《如何在 Spring/Spring Boot 中做参数校验?你需要了解的都在这里!open in new window》这篇文章
7. 全局处理 Controller 层异常#
相关注解:
@ControllerAdvice
:注解定义全局异常处理类@ExceptionHandler
:注解声明异常处理方法
如何使用呢?拿我们在第 5 节参数校验这块来举例子。如果方法参数不对的话就会抛出MethodArgumentNotValidException
,我们来处理这个异常。
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {
/**
* 请求参数异常处理
*/
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<?> handleMethodArgumentNotValidException(MethodArgumentNotValidException ex, HttpServletRequest request) {
......
}
}
更多关于 Spring Boot 异常处理的内容,请看我的这两篇文章:
作者:stdxiaozhang
出处:https://www.cnblogs.com/stdxiaozhang/p/16891333.html
版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。
吼吼,如果对你有帮助的话,可以点个赞呀!
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 我与微信审核的“相爱相杀”看个人小程序副业
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· spring官宣接入deepseek,真的太香了~