First, some code:
interface Foo {
void bar();
}
@Configuration
class FooConfig {
@Bean
public Foo foo() { return new MagicFoo(); }
class MagicFoo implements Foo { ... }
}
@Component
class FooImpl implements Foo {
public void bar() { }
}
@Component
class BarImpl {
final Foo foo;
public BarImpl(Foo foo) { this.foo = foo; }
}
As this example stands, when BarImpl
is instantiated, the Spring framework will look for a bean matching Foo
and prefer the bean defined by FooConfig
(i.e. the MagicFoo
) over the implementing-class FooImpl
.
My question is: is there any way to configure this code so that ONLY beans directly matching the interface (e.g. Foo
), and not any implementing classes (e.g. FooImpl
) are acceptable for a particular interface dependency? I.e. somehow configure Spring to treat Foo
dependencies in this special way.
In such a configuration, if I removed FooConfig
, I would get an error trying to instantiate BarImpl
because no suitable bean can be found, even though a bean for FooImpl
is available. In other words, with this desired configuration in place, the developer is forced to explicitly define beans for the identified interface instead of labeling implementing classes as beans.