I have a demo class FooComponent
which is autowired in FooService
and accessed in its constructor.
FooComponent.class:
@Component("fooComponent")
public class FooComponent {
public String format() {
return "foo";
}
}
FooService.class:
@Component
public class FooService {
@Autowired
private FooComponent fooComponent;
public FooService() {
System.out.println("in foo service const=" + this.fooComponent);
}
String doTatti() {
return fooComponent.format();
}
}
MainApplication:
@SpringBootApplication
public class InterviewApplication {
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(InterviewApplication.class, args);
System.out.println(ctx.getBean(FooService.class).doTatti());
}
}
In this tutorial, author says In the above example, Spring looks for and injects fooFormatter when FooService is created.
In my case, fooFormatter is fooComponent.
But everytime, in the constructor my autowired property is null. My assumption is that it is because FoOService
has not completely initialized? Is this correct?
If my assumption is correct, then why does below code work?
@Autowired
public FooService(FooComponent fooComponent) {
System.out.println("in foo service const=" + fooComponent);
}
I know this is very basic and stupid question, but I need help in understanding it.
UPDATE:
One last query, is there a way to Autowire
my FooService
instance in MainApplication
, instead of getting it from ApplicationContext
?
Thank you in advance.