【问题标题】:NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.mail.MailSender'NoSuchBeanDefinitionException:没有“org.springframework.mail.MailSender”类型的合格bean
【发布时间】:2020-06-10 02:30:34
【问题描述】:

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

【问题讨论】:

  • return new new JavaMailSenderImpl(); 你真的有两个new 关键字或者它在帖子中的错字吗?
  • 宁可使用 JavaMailSender,而不是 MailSender。
  • Karthikeyan Vaithilingam,这是一个错字。我编辑了这个

标签: java spring configuration javabeans spring-context


【解决方案1】:
  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注解 这将有助于自动配置。

【讨论】:

  • VIKASH,我的回答中省略了 bean 的内容。现在我通过添加属性编辑了我的答案
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2020-06-18
    • 1970-01-01
    • 2023-03-22
    • 2017-04-05
    • 2023-02-09
    • 1970-01-01
    • 2019-02-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多