I was expecting Spring to take @DependsOn
into account when calling @PostConstruct
methods, but seems like it's not the case in presence of circular (auto-wired) dependencies.
Consider two beans (code below), BeanB @DependsOn BeanA
. When field BeanA#b
has it's @Autowired
commented out, post-construct methods are called in expected order: first A, then B. But with @Autowired
in effect for A, I have B's post
called first, then A's post
.
I understand this is a bad design (actually, it's minimal demo of very big @Autowired
... code-base), but I was expecting Spring to finish injection of @Autowired
fields and then starting to call lifecycle callbacks, honoring @DependsOn
, but Spring seems to ignore @DependsOn
order when there are circular deps.
Spring version is 4.1.5.
So, is this my misunderstanding or undocumented behavior or can it be considered a Spring bug (or, perhaps, feature request)?
@Component
class BeanA {
// @Autowired
private BeanB b;
void f() {
System.out.println(this);
}
@PostConstruct
void post() {
System.out.println("A done");
}
@Override
public String toString() {
return "Bean{" +
"b=" + (b == null ? null : b.getClass()) +
'}';
}
}
// ---------------------
@Component
@DependsOn("beanA")
class BeanB {
@Autowired
private BeanA a;
void f() {
System.out.println(this);
}
@PostConstruct
void post() {
System.out.println("B done");
}
@Override
public String toString() {
return "BeanB{" +
"a=" + (a == null ? null : a.getClass()) +
'}';
}
}
See Question&Answers more detail:os