我对下面的场景几乎没有怀疑。
有一个接口(interface)和两个实现类:
接口(interface):
interface ServiceInt
{
public void save();
}
第一个实现类:
Public class ServiceIntImpOne implements ServiceInt
{
public void save()
{
// I am first service implementation
}
}
第二个实现类:
Public class ServiceIntImpTwo implements ServiceInt
{
public void save()
{
// I am Second service implementation
}
}
主类调用实现类的save方法:
Public class controller
{
@Autowired ServiceInt;
public void save()
{
ServiceInt.save()
}
}
我的问题:
ServiceInt.save()
– 它将调用服务类实现的哪个保存方法?- 我们如何使用
ServiceIntImpTwo
类的保存方法实现? - Autowiring 如何工作?
最佳答案
ServiceInt.save() – which save method of service class implementation will it invoke?
如果您有两个相同类型的 bean(通过注释或通过 xml 定义的 bean),当您 Autowiring 那个 bean 时,它将失败(抛出异常),因为 Spring 不知道要注入(inject)哪个 bean。
caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException:
No unique bean of type [ServiceInt] is defined:
How we can use the save method implementation of the ServiceIntImpTwo class?
如果您在 xml 文件中定义了 bean,那么您可以使用 id 属性
<bean id="beanTwo" class="ServiceIntImpTwo" />
然后你可以使用Qualifier注解 Autowiring
@Autowired
@Qualifier("beanTwo")
ServiceInt myServiceTwo;
如果您改用注解。
@Component
Class ServiceIntImpTwo impl...{}
然后你就可以 Autowiring 了
@Autowired
@Qualifier("serviceIntImpTwo ")
ServiceInt myServiceTwo;
How does autowired work?
您可以在 Internet 上阅读它。
http://memorynotfound.com/handling-multiple-autowire-dependencies-with-spring-qualifier/ https://www.mkyong.com/spring/spring-autowiring-qualifier-example/ https://www.tutorialspoint.com/spring/spring_qualifier_annotation.htm
关于带有服务实现的 Spring Autowired 注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39730016/