作者:的发个地方 | 来源:互联网 | 2023-05-19 18:10
这篇“Java依赖注入的方式是什么”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“Java依赖注入的方式是什么”文章吧。
Spring中的三种依赖注入方式
Field Injection :@Autowired注解的一大使用场景就是Field Injection
Constructor Injection :构造器注入,是我们日常最为推荐的一种使用方式Setter Injection:
Setter Injection也会用到@Autowired注解,但使用方式与Field Injection有所不同,Field Injection是用在成员变量上,而Setter Injection的时候,是用在成员变量的Setter函数上
// Field Injection
@Service("uploadService")
public class UploadServiceImpl extends ServiceImpl implements UploadService {
@Autowired
private UploadDao uploadDao;
}
// Constructor Injection
@Service("uploadService")
public class UploadServiceImpl extends ServiceImpl implements UploadService {
private UploadDao uploadDao;
UploadServiceImpl(UploadDao uploadDao){
this.uploadDao = uploadDao;
}
}
// Setter Injection
@Service("uploadService")
public class UploadServiceImpl extends ServiceImpl implements UploadService {
private UploadDao uploadDao;
@Autowired
public void setUploadDao(UploadDao uploadDao){
this.uploadDao =uploadDao
}
}
1.是否进行循环依赖检测
可能遇到的问题
循环依赖报错: 当服务A需要用到服务B时,并且服务B又需要用到服务A时,Spring在初始化创建Bean时,不知道应该先创建哪一个,就会出现该报错。
This is often the result of over-eager type matching - consider using 'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example
class ServerA{
@Autowired
private ServerB b;
}
class ServerB{
@Autowired
private ServerA a;
}
如果使用构造方式注入,能够精准的提醒你是哪两个类产生了循环依赖 .异常报错信息能够迅速定位问题:
循环报错解决办法是使用 @Lazy注解 ,对任意一个需要被注入Bean添加该注解,表示延迟创建即可。
class ServerA{
@Autowired
@Lazy
private ServerB b;
}
class ServerB{
@Autowired
@Lazy
private ServerA a;
}
以上就是关于“Java依赖注入的方式是什么”这篇文章的内容,相信大家都有了一定的了解,希望小编分享的内容对大家有帮助,若想了解更多相关的知识内容,请关注编程笔记行业资讯频道。