java - Spring 在基本 Spring Boot 应用程序中找不到 bean
问题描述
我是 Spring Boot 的新手,并将一个应用程序与一个 DemoApplication(主类)和一个名为 CodeChallenge 的类放在一起。这两个类都在同一个文件夹中。我将 CodeChallenge 类自动连接到主类中并正在使用 @EventListener(ApplicationReadyEvent.class)
,因此该类将在编译时触发。但是,每当我编译应用程序时,都会出现以下错误:
Field codechallenge in com.example.demo.DemoApplication required a bean of
type 'com.example.demo.CodeChallenge' that could not be found.
如何成功配置此应用程序,以便在编译程序时避免此错误并运行 CodeChallenge 类和 testMethod?
DemoApplication 类是:
package com.example.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
@SpringBootApplication
public class DemoApplication {
@Autowired
private CodeChallenge codechallenge;
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@EventListener(ApplicationReadyEvent.class)
public void callTestMethod() {
codechallenge.testMethod();
}
}
CodeChallenge 类是:
package com.example.demo;
public class CodeChallenge {
public void testMethod() {
System.out.println("hello world");
}
}
解决方案
您必须添加一个@Service
or@Component
注释public class CodeChallenge
才能让 Spring 知道那是一个 bean。
@Service
public class CodeChallenge {
public void testMethod() {
System.out.println("hello world");
}
}
推荐阅读
- maven - 子项目不从 Super POM 获取依赖项
- redmine - Redmine API 获取时间条目报告
- vue.js - 如何复制 VueJS 项目?
- tsql - CREATE FUNCTION 失败,因为没有为第 1 列指定列名。函数的 Multiple 参数出错
- android - Lottie Android - 如何从一个位置到另一个位置并按范围重复?
- c# - java.lang.IllegalArgumentException:没有这样的服务 ComponentInfo{/com.SampleApp.AttendanceApp.ServiceClass}
- c# - 文件复制中的 UnauthorizedAccessException
- intellij-idea - 如何使用 WebSphere 热交换 Intellij 中的 .xhtml 文件
- angular - 如何通过 codigniter API 在 Angular 8 HTTP 请求中使用 *application/x-www-form-urlencoded*
- java - 无法使用文件中的类路径和 cli 上的 @ 使用来运行 java 程序