How to overwrite Spring service beans by name, using annotations only

Lars Blumberg picture Lars Blumberg · Apr 7, 2011 · Viewed 38.1k times · Source

Given I have a Spring bean configured as

@Service("myService")
public class DefaultService extends MyService {
}

and a class using this bean

public class Consumer {
    @Autowired
    @Qualifier("myService")
    private MyService service;
    ...
}

I now want my project, that includes the preceding classes, to have Consumer another implementation of MyService being injected. Therefore I would like to overwrite the bean myService

@Service("myService")
public class SpecializedService implements MyService {
}

resulting in Consumer carrying now an instance of SpecializedService instead of DefaultService. By definition I cannot have two beans with the same name in the Spring container. How can I tell spring, that the definition of the new service shall overwrite the older one? I don't want to modify the Consumer class.

Answer

user41871 picture user41871 · Apr 7, 2011

Either define the service bean explicitly

<bean id="myService" class="x.y.z.SpecializedService" />

or component-scan it.

In either event, in your application context, avoid explicitly defining DefaultService and avoid component-scanning it.