【发布时间】:2020-04-13 18:08:40
【问题描述】:
我在 Spring 网站上关注此 SpringBoot Demo 以了解如何创建一个接受上传的文件。我收到一条错误消息:
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 0 of constructor in com.example.springdemouploadingfiles.FileUploadController required a bean of type 'com.example.springdemouploadingfiles.storage.StorageService' that could not be found.
Action:
Consider defining a bean of type 'com.example.springdemouploadingfiles.storage.StorageService' in your configuration.
Execution failed for task ':bootRun'.
Process 'command '/Applications/IntelliJ IDEA CE.app/Contents/jbr/Contents/Home/bin/java'' finished with non-zero exit value 1
- 我尝试通过向 FileUploadController 添加
@Bean注释来修复它。 - 我尝试添加以下依赖项
implementation 'org.springframework.boot:spring-boot-starter-data-jpa' runtimeOnly 'com.h2database:h2'构建.gradle - 注意:我不想将数据库连接到这个演示项目。该演示承认它不是在此演示中尝试连接数据库,而是在生产环境中我们会这样做。
- 我尝试在存储服务接口上方添加
@Service注释。 - 我尝试在 StorageService 接口上方添加
@Component。 - 我尝试在主应用程序类
SpringDemoUploadingFilesApplication.java上方添加@ComponentScan("com.example.springdemouploadingfiles")注释。
无论如何,我都希望得到一些帮助来解决这个错误,以便我可以运行演示。下面是我的配置。
build.gradle
plugins {
id 'org.springframework.boot' version '2.2.6.RELEASE'
id 'io.spring.dependency-management' version '1.0.9.RELEASE'
id 'java'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
runtimeOnly 'com.h2database:h2'
testImplementation('org.springframework.boot:spring-boot-starter-test') {
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}
}
test {
useJUnitPlatform()
}
FileUploadController.java
@Controller
public class FileUploadController {
private final StorageService storageService;
@Autowired
public FileUploadController(StorageService storageService) {
this.storageService = storageService;
}
SpringDemoUploadingFilesApplication.java
@SpringBootApplication
@EnableConfigurationProperties(StorageProperties.class)
public class SpringDemoUploadingFilesApplication {
public static void main(String[] args) {
SpringApplication.run(SpringDemoUploadingFilesApplication.class, args);
}
@Bean
CommandLineRunner init(StorageService storageService) {
return (args) -> {
storageService.deleteAll();
storageService.init();
};
}
}
StorageService接口
@Service
public interface StorageService {
// implements interface.
}
【问题讨论】:
-
StorageService 是您自己创建的类吗?如果是这样,请在该类的顶部添加 @Component。
-
storageService的代码在哪里?
-
是的,我有一个 StorageService 接口,我只是尝试了 StorageService 上面的@Service 注解,但没有成功。
-
@AbigailHowe:您需要创建一个实现 StorageService 的具体类并将 Service 注释放在那里。请参阅下面的答案。
标签: java spring spring-boot gradle