I found the following unorthodox configuration in my code base the other day and it made me wonder. What is the expected Spring Context behavior when I use an interface name also as the name of a bean? Would it make a difference if I was using @Autowiring in my Controller? The following snippet illustrates this setup:
interface MyAppService {...}
class InfrastructureService implements MyAppService {...}
class AdministrationService implements MyAppService {...}
class InfrastructureController {
// some code
public void setMyAppService(MyAppService svc){...}
}
<bean id="myAppService" class="InfrastructureService"/>
<bean id="administrationService" class="AdministrationService"/>
<bean id="infrastructureController" class="InfrastructureController">
<property name="myAppService" ref="myAppService"/>
</bean>
Alternatively, what would be the expected behaviour if only the controller was defined as:
class InfrastructureController {
@Autowired
public void setMyAppService(MyAppService svc){...}
}
Why should it matter here? You reference beans by
idin the xml, not by interface type.<property name="myAppService" ref="myAppService"/>This means that the property named
myAppServicewill have the bean with idmyAppServiceinjected. Nothing about interfaces.Edit: If you use autowiring with annotations and you have many different implementations of the same interface registered as components, then you have to use
qualifiersto tellSpringwhich implementation you gonna use. If you have only one implementation registered, no action is needed.