2016-10-31 168 views
0

在module1.jar:具有多个自动装配类型的依赖关系解决方案?

<bean id="customerService" class="com.service.CustomCustomerServiceImpl" > </bean> 

在module2.jar:

<bean id="customerService" class="com.service.CustomerServiceImpl" > </bean> 


public class CustomerController { 
    @Autowired 
    protected CustomerService customerService; 

// getters and setters 
} 

我看到的CustomerService与CustomCustomerServiceImpl总是注射。

我的问题是,在启动服务器 时应该抛出异常,因为有两个类型为CustomerService的Bean(CustomCustomerServiceImpl和CustomerServiceImpl)。

不应该弹出异常?

当多个bean被发现时,spring如何通过type来解析autowire注解?

更新: -

public class CustomCustomerServiceImpl extends CustomerServiceImpl {} 
+1

由于您为每个bean设置了一个'id',因此Spring会尝试将bean'id'与您要注入的属性的名称进行匹配。因此,您将始终注入'customerService',因为这是您的类属性的名称。如果你没有为bean设置'id',那么是的,你可能会得到一个异常。 – icabod

+0

@icabod两个id都是一样的。所以'CustomCustomerServiceImpl'如何被注入而不是错误? – user3198603

+0

几分钟前,这些id不一样,其中一个bean有另一个作为父项,意味着它可以覆盖基本bean。 – icabod

回答

0

应该不是春抛出异常?如果发现多个 豆类,弹簧如何能够在此处按类型解析自动布线?

如果某些类名发生冲突,那么JVM将尝试从类路径中较早出现的jar中加载它们。因此,Spring不会抛出任何异常,它首先从JAR加载(假设为CustomerServiceImpl implements CustomerService),它只是CustomerServiceImpl中的类autowires

请参阅here了解有关类加载如何工作的更多详细信息。

+0

我认为类加载是不同于字符串DI的东西。如果Spring无法解析要注入哪个Bean,则应该ge'UnsatisfiedDependencyException'。 –

相关问题