Spring无法在基本的Spring Boot应用中找到bean

时间:2019-02-08 06:47:14

标签: java spring spring-boot

我是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");
    }
}

1 个答案:

答案 0 :(得分:4)

您必须在@Service上添加@Componentpublic class CodeChallenge注释,以使Spring知道多数民众赞成在一个豆上。

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