I am learning Spring Dependency Injections and to do so I wrote small simple code, but I constanstly get this error:
No qualifying bean of type available available: expected at least 1 bean which qualifies as autowire candidate.
Can anyone point me in the right direction? Thanks!
Service.java
package net.ddns.encante.test2.Spring.SpringTest2;
import org.springframework.stereotype.Component;
@Component
public class Service {
void doService (){
System.out.println("Service is running");
}
}
Controller.java
package net.ddns.encante.test2.Spring.SpringTest2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class Controller {
@Autowired
Service service;
void doControl(){
System.out.println("Controlling, move along");
}
void doServiceByController(){
service.doService();
}
}
SpringTest2Application.java
package net.ddns.encante.test2.Spring.SpringTest2;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
@SpringBootApplication
public class SpringTest2Application {
public static void main(String[] args) {
SpringApplication.run(SpringTest2Application.class, args);
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(Controller.class);
ctx.refresh();
Controller ctrl = ctx.getBean(Controller.class);
ctrl.doServiceByController();
}
}
I tried different combinations of @Component and @Autowired annotations but it doesn't help.
CodePudding user response:
The problem is your code.
SpringApplication.run(SpringTest2Application.class, args);
This already creates everything you need. However you discard it and try to shoehorn something in there.
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(Controller.class);
ctx.refresh();
Controller ctrl = ctx.getBean(Controller.class);
ctrl.doServiceByController();
This will create another application context, and only for the Controller
nothing else.
Instead, if you read the javadoc of the run
method you can see that that already returns an ApplicationContext
. Which is the one you should be using in the first place.
ApplicationContext ctx = SpringApplication.run(SpringTest2Application.class, args);
Controller ctrl = ctx.getBean(Controller.class);
ctrl.doServiceByController();
Is all you need.