![](/img/trans.png)
[英]Spring unit test results in NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.mail.javamail.JavaMailSender'
[英]NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.mail.MailSender'
我试图通过自动装配 SpringContext 在我的 ApplicationListener 中使用 MailSender:
package example.util.emailUtil;
@Component
public class PostUserListener implements ApplicationListener<OnPostUserDataEvent> {
@Autowired
private MailSender mailSender;
}
配置类是:
@ComponentScan(basePackages ={"example.util.emailUtil","example.model","example.service"})
@Configuration
public class MailProvider {
@Bean(name = "mailSender")
public MailSender javaMailService()
JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
javaMailSender.setHost("smtp.gmail.com");
javaMailSender.setPort(587);
javaMailSender.setProtocol("smtp");
javaMailSender.setUsername("sender’s email");
javaMailSender.setPassword("sender’s password");
Properties mailProperties = new Properties();
mailProperties.put("mail.smtp.auth", "true");
mailProperties.put("mail.smtp.starttls.enable", "true");
mailProperties.put("mail.smtp.debug", "true");
javaMailSender.setJavaMailProperties(mailProperties);
return javaMailSender;
}
}
但我发现了以下例外情况:
NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.mail.MailSender' available: expected at least 1 bean which qualifies as autowire candidat
检查 application.properties 中的以下内容
spring.mail.host=smtp.xxx.com spring.mail.username=xxx@xxx.com spring.mail.password=xxxxx spring.mail.properties.mail.smtp.auth=true spring.mail.properties.mail.smtp.starttls.enable=true spring.mail.properties.mail.smtp.starttls.required=true
如果您使用的是 Spring Boot 应用程序,请使用 @EnableAutoConfiguration 注释,这将有助于自动配置。
它不会将您的 MailSender 类视为可以使用 @autowired 进行注释的类或我们可以注入的 bean。 并检查您是否添加了@component、@service 或其他注释。 也许还会有其他错误。 这是从那里来的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.