学会这个,从此告别@Autowired

第一次写,稍有不慎,见谅,话不多说 进入正题

之前的编码都是一贯使用@Autowired.用到什么注入什么,@autowired满天飞
在此介绍一个可以简化代码的插件lombok (官方API) -->https://projectlombok.org/features/all

public class TestController{

    private final TestService testService;

    public void  test() {
		testService.test()
    }

}

再看TestService

@RequiredArgsConstructor
public class TestService {
	private final TestMapper testMapper
	public void test(){
		........
	}
}   

@RequiredArgsConstructor是lombok的一个注解,它主要用来做什么的呢?

官方给出的解释是:
Generates constructor that takes one argument per final / non-null field.
所以它会为final和nonnull的属性作为参数产生一个构造函数。

spring的官方解释中:

Starting with Spring 4.3, if a class, which is configured as a Spring bean, has only one constructor, the Autowired annotation can be omitted and Spring will use that constructor and inject all necessary dependencies.
Regarding the default constructor: You either need the default constructor, a constructor with the Autowired annotation when you have multiple constructors, or only one constructor in your class with or without the Autowired annotation.

**结论就是:

If a class, which is configured as a Spring bean, has only one constructor, the Autowired annotation can be omitted and Spring will use that constructor and inject all necessary dependencies.
如果一个类(配置为Spring bean)只有一个构造函数,那么可以省略自动生成的注释,Spring将使用这个构造函数并注入所有必要的依赖项。

以上仅是一种编码风格,并不是@Autowired会被替代

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值