I have two classes and I want to inject one class into another using Spring
public class A {
private B b;
...
}
@Component
public class B {
...
}
But when I try to call b object method i cath NullPointerException. And I didn't understand why Spring didn't inject bean in A class. Can someone explain to me what's wrong?
I have read all the Spring documentation in the world and have not found a solution.
CodePudding user response:
Note that according to your code A is not managed by Spring (it is not annotated by it), and therefore, nothing instantiates B
To solve this you should mark A as a component as well:
@Component
public class A {
private B b;
...
}
@Component
public class B {
...
}
Moreover, it's always better to use constructor injection over property injection and/or setter-getter injections, so long story short I would suggest this approach:
@Component
public class A {
private final B b;
public A(final B b) {
this.b = b;
}
}
@Component
public class B {
...
}
CodePudding user response:
You only have allowed your Class B
to be treated as Spring Bean (Managed by Spring Bean Lifecycle) by annotating it with @Component
. That's fine. But you haven't done same with Class A
. Spring does not know about this class and does not manage it, so it will not provide you with a reference of B
into A
.
You can use constructor based injection
@Component
public class A {
private final B b;
@Autowired
public A(B b){
this.b = b;
}
// other methods
}
@Component
public class B {
...
}
CodePudding user response:
You should use the @Autowiring annotation on the b field. That fix your problem