我有一个带有此配置文件的 SpringBoot 应用程序:
package com.bonanza.web.config;
@Configuration
@EnableJpaRepositories(basePackages = "com.bonanza.backend.repository")
@EntityScan(basePackages = "com.bonanza.backend")
@EnableTransactionManagement
@EnableCaching
@PropertySource("file:///${user.home}/.bonanza/application-common.properties")
public class BonanzaApplicationConfig {
}
以及此服务:
package com.bonanza.backend.service;
@Service
@Transactional(
readOnly = true
)
public class UserService {
private final RoleRepository roleRepository;
private final UserRepository userRepository;
private final PasswordEncoder passwordEncoder;
private final PasswordResetTokenRepository passwordResetTokenRepository;
public UserService(RoleRepository roleRepository, UserRepository userRepository, PasswordEncoder passwordEncoder, PasswordResetTokenRepository passwordResetTokenRepository) {
this.roleRepository = roleRepository;
this.userRepository = userRepository;
this.passwordEncoder = passwordEncoder;
this.passwordResetTokenRepository = passwordResetTokenRepository;
}
..
}
和主类:
package com.bonanza.web
@SpringBootApplication
public class BonanzaWebApplication {
public static void main(String[] args) {
SpringApplication.run(BonanzaWebApplication.class, args);
}
}
和这个 Controller
package com.bonanza.web.controller;
@Controller
public class AppErrorController implements ErrorController {
protected final UserService userService;
..
public AppErrorController(UserService userService, ErrorAttributes errorAttributes, EmailService emailService) {
super(userService);
this.errorAttributes = errorAttributes;
this.emailService = emailService;
}
...
}
但是当我启动应用程序时。我有这个错误:
Description:
Parameter 0 of constructor in com.bonanza.web.controller.AppErrorController required a bean of type 'com.bonanza.backend.service.UserService' that could not be found.
Action:
Consider defining a bean of type 'com.bonanza.backend.service.UserService' in your configuration.
最佳答案
@SpringBootApplication ,只会搜索当前包及其所有子包中的组件/bean。您的UserService
包
com.bonanza.backend.service
不是 BonanzaWebApplication
的子包
com.bonanza.web
这样就可以与所有需要组件扫描的包一起使用
@ComponentScan({"com.bonanza.web","com.bonanza.backend.service"})
@SpringBootApplication
public class BonanzaWebApplication {
public static void main(String[] args) {
SpringApplication.run(BonanzaWebApplication.class, args);
}
}
您还可以在 @SpringBootApplication 中指定组件扫描自己注释
@SpringBootApplication(scanBasePackages = {"com.bonanza.web","com.bonanza.backend.service"})
关于java - 错误 init SpringBoot v.2.1.10.RELEASE app 构造函数参数 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58905222/