Search code examples
javaspring-bootspring-mvcspring-annotations

Bean error while printing Hello world with spring boot mvc model


I'm trying to print hello world with java spring boot MVC adding annotations but it generates this error that indicates that Spring could not find a bean of com.example.HelloWorld.service.BusinessService when attempting to inject it into the HelloWorldApplication class.

Even if I created a bean type withthe annotation @Component

Field bs in com.example.HelloWorld.HelloWorldApplication required a bean of type 'com.example.HelloWorld.service.BusinessService' that could not be found.

The injection point has the following annotations:
    - `@org.springframework.beans.factory.annotation.Autowired(required=true)`


Action:

Consider defining a bean of type 'com.example.HelloWorld.service.BusinessService' in your configuration.

I added @component in the bean class and @autowired while declaring the variable but don't understant why I have the bean's error

    package com.example.HelloWorld;

@SpringBootApplication
public class HelloWorldApplication implements CommandLineRunner {

    @Autowired
    private BusinessService bs; 

    public static void main(String[] args) {
        SpringApplication.run(HelloWorldApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        HelloWorld hw = bs.getHelloWorld();
        System.out.println(hw);
    }
}

package com.example.HelloWorld.service;

import org.springframework.stereotype.Component;

import com.example.HelloWorld.model.HelloWorld; 

@Component
public class BusinessService {
    
    public HelloWorld getHelloWorld() {
        HelloWorld hw = new HelloWorld();
        return hw;
    }
}


package com.example.HelloWorld.model;

public class HelloWorld {
    private String value = "Hello World !";

    public String getValue(){
        return value;
    }

    public void setValue(String value){
        this.value = value;
    }

    @Override
    public String toString(){
        return value;
    }


}

Thanks for helping


Solution

  • What you could do is create a configuration class:

    @org.springframework.context.annotation.Configuration
    public class Configuration
    {
        @Bean
        BusinessService businessService() {
            return new BusinessService();
        }
    }
    

    and in your main class inject this service via constructor:

    public class HelloWorldApplication implements CommandLineRunner {
    
        private BusinessService bs;
        public HelloWorldApplication(BusinessService bs)
        {
            this.bs = bs;
        } ...
    }