java - Spring 在基本 Spring Boot 应用程序中找不到 bean

标签 java spring spring-boot

我是 Spring Boot 的新手,并将一个应用程序与 DemoApplication(主类)和一个名为 CodeChallenge 的类放在一起。这两个类都位于同一文件夹中。我将 CodeChallenge 类 Autowiring 到主类中,并使用 @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");
    }
}

最佳答案

您必须在 public class CodeChallenge 上添加 @Service@Component 注释,让 Spring 知道这是一个 bean。

@Service
public class CodeChallenge {
    public void testMethod() { 
        System.out.println("hello world");
    }
}

关于java - Spring 在基本 Spring Boot 应用程序中找不到 bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54587270/

相关文章:

java - 将 swagger2-ui 与 spring-boot 一起使用时出现 404

java - 如何控制 Spring bean 创建的顺序?

spring - 使用 Spring Security 3.2.0.RELEASE,如何在没有标签库的纯 HTML 页面中获取 CSRF token

java - 如何一起使用 mapstruct 和 springboot bean? @autowired

java - JOGL 2.0 不支持 GLCanvas ,Texture ,Animator ,但是 jogl 1.0 呢?

java - 使用 Mallet 进行朴素贝叶斯分类 : How and where are Alphabets set up?

spring - 如何在 SpringJunit4TestRunner 中将 @ComponentScan 与特定于测试的 ContextConfigurations 一起使用?

spring - 使用 HttpEntity<List> 在 Spring RestTemplate 中删除

java - 是什么让这个 Clojure 函数变慢了?

java - 更新 JPA 表上的 UniqueConstrains