Java Spring 方法参数需要一个无法找到的 Bean

标签 java spring spring-boot

我正在编写一个发送电子邮件的 Java Spring 应用程序。我正在从 SQL 数据库检索数据(电子邮件地址)。我导入了我需要的数据库存储库,但 Spring 无法注入(inject)该依赖项。我的邮件服务如下所示:

@Service
public class MailService {

    private final Logger log = LoggerFactory.getLogger(MailService.class);
    private final static String USER = "user";
    private final String baseUrl;
    private final ApplicationProperties applicationProperties;
    private final JavaMailSenderImpl javaMailSender;
    private final MessageSource messageSource;
    private final SpringTemplateEngine templateEngine;
    private UserRepository userRepository;

    @Autowired
    public void setUserRepository(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    public MailService(ApplicationProperties applicationProperties, JavaMailSenderImpl javaMailSender,
                       MessageSource messageSource, SpringTemplateEngine templateEngine) {

        this.applicationProperties = applicationProperties;
        this.javaMailSender = javaMailSender;
        this.messageSource = messageSource;
        this.templateEngine = templateEngine;
        baseUrl = applicationProperties.getBaseUrl();

        javaMailSender.setPort(applicationProperties.getPort());
        javaMailSender.setHost(applicationProperties.getHostName());
    } 

我得到的错误是:

***************************
APPLICATION FAILED TO START
***************************

Description:

Parameter 0 of method setUserRepository in com.test.mail.service.MailService required a bean of type 'com.test.repository.UserRepository' that could not be found.

The injection point has the following annotations:
    - @org.springframework.beans.factory.annotation.Autowired(required=true)


Action:

Consider defining a bean of type 'com.test.repository.UserRepository' in your configuration.

有人知道这可能是什么吗?谢谢。

最佳答案

正如注释中所保留的那样:应添加@ComponentScan。 例如:

@ComponentScan(basePackages = "com.test.repository")
@Configuration
public class SpringComponentScanApp {

关于Java Spring 方法参数需要一个无法找到的 Bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59777199/

相关文章:

java - Observablelist 和 arraylist,不同的行为

java - java中的 headless 异常

java - 如何在 Spring Boot 应用程序中配置 DispatcherServlet?

java - 如何使用 IntelliJ 在 Maven 中解决 "java: package com.opencsv does not exist"?

spring - 当management.port=0时,在运行时获取Spring Boot管理端口

java - Java对象的write-behind缓存解决方案,使用oracle stored procs进行持久化

java - java Scanner 类中的 nextLine()、hasNextLine() 和 NoSuchElementException

java - 有 header 时请求映射不起作用

java - 从 ServletContext 资源解析 XML 文档时出现意外异常 [/WEB-INF/applicationContext.xml];

java - springdoc-openapi 通用 Controller 类型参数支持