0

Usually, we use @Componenet right? and also specialized forms @Controller, and @Service for particular classes. So those annotations are responsible to create beans during the spring app creation, correct?

My current problem is I have a particular dependency. Inside that dependency, it is @Autowire another class, let's say classB. But that classB doesn't have any class-level annotation such as @Compoenent.

ex.

public class classA {
  @Autowired
  private ClassB classB;
}

public class classB {
 // logic....
}

So when I try to run the app, I get an error something like this -- please ignore the class name and package name..

Field demoService in com.example.demo.controller.DemoController required a bean of type 'com.example.demo.service.DemoService' that could not be found.

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

And like I said before, those are from dependency jar so I can't really edit, they are read-only file.

I am thinking about to have config class like below

@Configuration
public class Config {

    @Bean
    public DemoService myDemoService(){
        return new DemoService();
    }

I am not sure if it's going to work or not.

Do you have different ideas?

Thank you for reading my question

I haven't tried the config class. Looking for other people's ideas, experience , how to resolve this

seenukarthi
  • 8,241
  • 10
  • 47
  • 68
lusjjj
  • 1

2 Answers2

3

The creation of the DemoService Bean in the configuration class is the right approach. There are two ways you can create a bean in Spring, one by adding the @Component annotation and allowing spring to create the object or by specifying the bean in the configuration class.

There is however another way to achieve this. This is documented in the link. Essentially, you create an initiation of the DemoService and auto wire dynamically in the code.

Avishek Bhattacharya
  • 6,534
  • 3
  • 34
  • 53
0

Creating config class would also work correctly. If you don't want to create a new class, define that bean inside application class i.e where you're using @SpringBootApplication annotation or from where you're running the application.