Reputation: 364
I am trying to understand how the Autowiring works in the SPringBoot. So, I had created a singketon class B [for example] and I was processing the instance of class B in class C and now want to use that in class A. It was all working fine. But, now I was told to use Auto wiring as my application is springBoot. So I did following
@Component
Class B{
int track = 0;
}
Class C{
@Autowired
B b
public void doSomething(){
b.track = 1;
}
}
Class A{
// I want to use the object b in here for further processing, how can I do it ?
}
Am I doing it right ? Or How can I achieve this please ?
Upvotes: 0
Views: 45
Reputation: 1717
For starters, you should consider using @Autowired on your constructors, as it lets you [avoid null pointer exceptions][1] if something isn't wired properly.
If you want to autowire B into A, do it the same way as you did with C; just make sure you avoid circular dependencies.
@Component
Class B{
int track = 0;
}
Class C{
private final B b;
@Autowired
public C(B b){
this.b = b;
}
public void doSomething(){
b.track = 1;
}
}
Class A{
private final B b;
@Autowired
public A(B b){
this.b = b;
}
}
[1]: http://evan.bottch.com/2009/02/03/setter-injection-sucks/ <- This is an oldie but a goodie; also see http://olivergierke.de/2013/11/why-field-injection-is-evil/
Upvotes: 1