如何使用@AllArgsConstructor和final 代替 @Autowired

网友投稿 1619 2022-12-05

如何使用@AllArgsConstructor和final 代替 @Autowired

如何使用@AllArgsConstructor和final 代替 @Autowired

目录@AllArgsConstructor和final 代替 @Autowiredspring代替 @Autowired(lombok相关注解)注解遇到坑

@AllArgsConstructor和final 代替 @Autowired

Springboot官方建议使用final来修饰成员变量,然后通过构造方法来进行注入原因:final修饰的成员变量是不能够被修改的,反射那就没办法了。

spring代替 @Autowired(lombok相关注解)

前提:使用lombok

@Slf4j

@RestController

//生成一个包含过所有字段的构造方法

//@AllArgsConstructor

//会将类的每一个final字段或者non-null字段生成一个构造方法

@RequiredArgsConstructor

public class AdminUserController {

/* autowired没什么问题,但是有可能报错,iUserService为null,spring也不建议使用autowired */

//@Autowired

//private IUserService iUserServicehttp://;

private final IUserService iUserService;

@PostMapping("/login")

public Result adminLogin(HttpServletResponse response, String username,String password) {

//....

}

}

注解

@NoArgsConstructor后会 生成无参的构造方法

@RequiredArgsConstructor会将类的每一个final字段或者non-null字段生成一个构造方法

@AllArgsConhttp://sthttp://ructor 生成一个包含过所有字段的构造方法。

@AllArgsConstructor 和@RequiredArgsConstructor都可以用来替换@Autowired写法,区别在@RequiredArgsConstructor必须要有final修饰。

遇到坑

使用@AllArgsConstructor后,@Value会失效,获取不到值。使用@RequiredArgsConstructor则正常。今后注入service、mapper等都使用@RequiredArgsConstructor好了。

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:物联网小程序开发是什么?如何选择物联网小程序开发公司?
下一篇:基于@AllArgsConstructor与@Value共用的问题解决
相关文章

 发表评论

暂时没有评论,来抢沙发吧~