1

我正在尝试通过自动装配 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
4

2 回答 2

0
  1. 检查您的 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
    
  2. 如果您使用的是 Spring Boot 应用程序,请使用 @EnableAutoConfiguration 注释,这将有助于自动配置。

于 2020-02-26T09:10:34.060 回答
0

它不会将您的 MailSender 类视为可以使用 @autowired 注释的类或我们可以注入的 bean。并检查您是否向其添加了@component、@service 或其他注释。也许还会有其他错误。这个来自那里。

于 2020-02-26T13:48:23.537 回答