【发布时间】:2021-08-06 01:54:11
【问题描述】:
请帮助我了解当实现类扩展另一个类时,自动装配如何与 Spring 中的接口一起工作。由于我们无法在Java中为接口创建对象,我的理解是Spring在使用@Autowired注解时会注入实现类的实例。在以下情况下,为什么在 TestServiceImpl 中自动装配 TestDAO 时无法调用继承方法( TestDAOImpl->save() )?
Interface CommonDAO
{
save();
}
Class CommonDAOImpl implements CommonDAO
{
// define save();
}
Interface TestDAO
{
User createUser ()
}
class TestDAOImpl extends CommonDaoImpl{
//define createUser()
}
class TestServiceImpl implements TestService{
@Autowired
TestDAO testDao
public User createUser(){
//Able to call testDao.createUser();
//Why I am not able to call call testDao.save()?
//what is actually happening when autowiring interface? Spring not injecting instance for TestDAOImpl in this case?
}
}
【问题讨论】:
-
您的示例不起作用。您有一个类试图“实现”另一个类,并且您有两个不相关的接口。 (类实现接口
A和B的事实并不意味着如果您将其变量声明为A,您也会看到B方法。) -
我认为你必须
@Autowired使用TestDAOImpl类,而不是接口。而mapper-config.xml 会搜索所有DAO,并与sql mapper xmls 绑定 -
你的班级只知道
TestDAO它不知道TestDAOImpl。由于TestDAO不是CommonDAO,因此save方法不可用,无论使用哪种实现。 -
这与 Spring 无关,而只是接口在 Java 中的工作方式。做你想做的事,你要么需要注入
CommonDAO,要么确保TestDAO扩展CommonDAO。
标签: java spring interface autowired