我正在编写一个发送电子邮件的 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/