0

I am new to Spring Boot and put an application together with a DemoApplication (main class) and a class called CodeChallenge. Both of these classes are in the same folder. I autowired the CodeChallenge class into the main class and am using @EventListener(ApplicationReadyEvent.class) so the class will trigger when it is compiled. However, whenever I compile the app I get the following error:

Field codechallenge in com.example.demo.DemoApplication required a bean of 
type 'com.example.demo.CodeChallenge' that could not be found.

How can I successfully configure this application so I can avoid this error and run the CodeChallenge class and testMethod when compiling the program?

The DemoApplication class is:

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();   
      }

}

And the CodeChallenge class is:

package com.example.demo;

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

1 Answer 1

4

You have to add a @Service or @Component annotation on public class CodeChallenge to let Spring know thats a bean.

@Service
public class CodeChallenge {
    public void testMethod() { 
        System.out.println("hello world");
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.