How to rewrite Spring beans service by name using only annotations

Given that I have a Spring bean configured as

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

and class using this bean

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

Now I want my project, including the previous classes, to have the Consumerfollowing implementation MyService. So I would like to rewrite beanMyService

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

resulting in Consumertransferring the instance SpecializedServiceinstead DefaultService. By definition, I cannot have two beans with the same name in a Spring container. How can I tell spring that the definition of a new service should rewrite the older one? I do not want to change the class Consumer.

+5
source share
4

bean

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

- .

DefaultService .

+2

<component-scan base-package="your-package">
    <exclude-filter type="regex" expression="DefaultService" />
</component-scan>

, ( @Service DefaultService).

+2

XML, , beans, XML, , . , XML, ,

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

Spring XML beans MVC beans. @Autowired . , ( ).

-, @Qualifiers ( "id bean" ), .

0

, . .

MyService.

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

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

(, ) @Qualifier , .

@Autowired
@Qualifier("myService")
MyService myService;   

@Autowired
@Qualifier("mySpecializedService")
MyService myService;
-2

All Articles