spring Boot @Autowired注入

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_16909139/article/details/85005087

Bspring boot @Autowired使用方式:

1.通过构造器注入
单个

public class TestController (){
private final TestMapper testMapper;
@Autowired
public TestController (TestMapper testMapper) {
this.testMapper= testMapper;
}
}
多个

public class TestController (){
private final TestaMapper testaMapper;
private final TestbMapper testbMapper;
@Autowired
public TestController (TestaMapper testaMapper, TestbMapper testbMapper) {
this.testaMapper= testaMapper;
this.testbMapper= testbMapper;
}
}

弊端:可以看出当需要注入更多的对象时,构造函数的参数值会变得很长。

2.通过setter方法注入

public class TestController (){
private final TestMapper testMapper;
@Autowired
public void setTestMapper(TestMapper testMapper) {
this.testMapper= testMapper;
}
}

弊端:不能将属性设置为final,每个对象的注入都要写对应的setter方法。

3.通过field反射注入

public class TestController (){
@Autowired
private TestMapper testMapper;

弊端:方法最简单。不符合JavaBean规范;不能将属性设置为final;创建的对象时,还可能引起NullPointerException。

使用idea时会提示Field injection is not recommended

作者:十月是妳的谎言
来源:CSDN
原文:https://blog.csdn.net/qq_38904700/article/details/79515049
版权声明:本文为博主原创文章,转载请附上博文链接!

猜你喜欢

转载自blog.csdn.net/qq_16909139/article/details/85005087