spring Boot @Autowired注入
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
版權宣告:本文為博主原創文章,轉載請附上博文連結!