How do you initialize this:
class A {
final B b;
A(B b) {
this.b = b;
}
}
class B {
final A a;
B(A a) {
this.a = a;
}
}
DI framework, reflection, better design?
Motivation and a use case (added):
My particular use case is simplifying field access in A
's and B
's sub-classes. So I'm injecting them to shortly reference them by fields in the derived classes without a need to declare explicitly in each sub-class.
There is also a recommendation on DI that objects should better be immutable: Guice best practices and anti-patterns.
Though it may look dirty, but I prefer to replace one of the
final
references withSupplier
(like one inGuava
orJava 8
) like:where
MutableSupplier
looks somehow like the following:I know that
MutableSupplier
's mutability looks super-ugly for immutability enthusiasts but I found that using it is more or less acceptable in such cases :)What you are having is a circular dependency. The only way I can think of is to not declare the fields as final and have your dependency injected using setter injection instead of constructor injection.
You could use a factory method