@RequiredArgsConstructor自动注入
时间: 2023-11-08 20:04:27 浏览: 51
@Autowired 和 @RequiredArgsConstructor 是 Spring 框架中用于自动注入依赖的注解。
@Autowired 注解用于自动装配 Spring 容器中匹配的 bean。通过在字段、构造函数、setter 方法上添加 @Autowired 注解,Spring 将会自动将匹配的 bean 注入到对应的变量或参数中。
@RequiredArgsConstructor 注解是 lombok 库提供的一个注解,用于生成带有 final 修饰的成员变量的构造函数。当我们使用 @RequiredArgsConstructor 注解时,会自动为所有 final 修饰的字段生成构造函数参数,并将它们作为构造函数的参数,方便我们进行依赖注入。
相关问题
@RequiredArgsConstructor 怎么注入
在使用@RequiredArgsConstructor注解时,可以通过两种方式将其注入到其他类中。一种方式是使用构造器注入,即在需要注入的类的构造器上使用@RequiredArgsConstructor注解。这样,在创建该类的实例时,相关的依赖会通过构造器自动注入进来。例如,在一个类中使用@RequiredArgsConstructor注解,然后在其他类中通过创建该类的实例来实现注入。另一种方式是使用@Autowired或@Resource等注解来注入。在需要注入的地方使用相应的注解,并指定要注入的类的类型。这样,在创建实例时会自动查找并注入相应的依赖。例如,在一个类中使用@RequiredArgsConstructor注解,在需要注入的地方使用@Autowired注解来注入该类的实例。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
@RequiredArgsConstructor
@RequiredArgsConstructor是Lombok的一个注解,用于简化对@Autowired的使用。在编写Controller层或Service层时,经常需要注入多个mapper接口或service接口,如果每个接口都手动写上@Autowired注解,会显得冗长繁琐。使用@RequiredArgsConstructor注解可以自动生成包含这些依赖的构造方法,从而避免手动注入的麻烦。
相比于@AllArgsConstructor注解,@RequiredArgsConstructor注解只会生成对类的final字段或者non-null字段进行赋值的构造方法。这意味着使用@RequiredArgsConstructor注解时,必须使用final修饰字段或者确保字段的值不为null。而使用@AllArgsConstructor注解时,会生成包含所有字段的构造方法。
总结一下:
- @RequiredArgsConstructor注解可用于简化@Autowired的使用,自动生成包含依赖的构造方法。
- @RequiredArgsConstructor只会为final字段或者non-null字段生成构造方法。
- @AllArgsConstructor会为所有字段生成构造方法,但在与@Value注解一起使用时会失效。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)