I have a problem with @Autowired inside bean. I’ve posted simplified code structure. I have two classes annotated with @Configuration and two simple beans. In class D autowired bean doesn’t injected. So I wonder is it posible to solve the NPE without changing structure?
Class A:
@Configuration
public class A {
@Autowired
private B b;
@Bean
publict Other other() {
b.doFoo();
Other other = new Other();
}
@Bean
public C c() {
return new C();
}
}
Class B:
@Configuration
public class B {
@Bean
public D d() {
return new D();
}
public void doFoo() {
d().doBar();
}
}
Class C inner structure of doesn’t matter. So class D:
public class D {
@Autowired
C c;
public void doBar() {
c.doFooBar(); // And here we got NPE
}
}
I’s must be noticed, that if I move initialization of bean D from B to A and autowired it to B everything works fine:
@Configuration
public class A {
@Autowired
private B b;
@Bean
publict Other other() {
b.doFoo();
Other other = new Other()
}
@Bean
public C c() {
return new C();
}
@Bean
public D d() {
return new D();
}
}
@Configuration
public class B {
@Autowired
private D d;
public void doFoo() {
d.doBar();
}
}
But this method doesn’t suit.
Let’s analyze class
Bfor second. In that class when you calldoFoo()method you have executedd().doBar();, which is like you manually created instance of classD, without any Spring. You calledd()method directly it is just like you puttednew D().doBar(). If you want toDbe created with spring add this in classB:and change your method
doFoo()to:Key part in your question was:
This is also an answer.