user689842
user689842

Reputation:

Spring behaviour when using interface name also as a bean name?

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){...}
}

Upvotes: 1

Views: 1558

Answers (2)

kundan bora
kundan bora

Reputation: 3889

If you put @AutoWired alone it search dependency by Type (In your case it is MyAppService).If you want to narrow down dependecy seaching you can use @Qualifier as below :

class InfrastructureController {
@Autowired
@Qualifier("NAME_OF_BEAN")
public void setMyAppService(MyAppService svc){...}
}

Upvotes: 0

Petar Minchev
Petar Minchev

Reputation: 47393

Why should it matter here? You reference beans by id in the xml, not by interface type.

<property name="myAppService" ref="myAppService"/>

This means that the property named myAppService will have the bean with id myAppService injected. 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 qualifiers to tell Spring which implementation you gonna use. If you have only one implementation registered, no action is needed.

Upvotes: 2

Related Questions