我的邮件服务具有构造函数参数并实现了一个接口(interface)
public class MailServiceImpl implements MailService {
private MailBo mail;
public MailBO getMail() {
return Mail;
}
public void setMail(MailBO Mail) {
this.Mail = Mail;
}
public MailServiceImpl(MailBo mail) {
throw exception if from and to address is not here
this.mail = mail;
}
public void sendMail(){
use mail object to send mail here
}
}
所以现在我正在尝试编写一个测试,我想创建 Autowiring 的 Mailserviceimpl 实例,并在其中传递构造函数参数。
我关注了this使用构造函数链接到 Autowiring 对象,但我遇到了异常
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.model.MailBO] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
我的测试课
public class MailServiceImplTest {
@Autowired
private MailService mailServiceImpl;
@Test
public void testSendValidMail(){
//test
}
}
编辑:-
添加 spring 上下文
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.service" />
</beans>
编辑2:- 我希望我的邮箱加载一些值并将其作为构造函数对象注入(inject)到 mailserviceimpl
最佳答案
我假设 MailServiceImpl
和 MailBO
是 Spring Bean。然后只需在 MailServiceImpl 构造函数上添加 @Autowired
注释,Spring 就会自动注入(inject)构造函数依赖
关于java - Spring Autowiring 依赖,具有构造函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21365643/