Java 不明确的自动关联,但不带限定符
我有一个服务,它向Bean注入@Autowired,如下所示Java 不明确的自动关联,但不带限定符,java,spring,inversion-of-control,Java,Spring,Inversion Of Control,我有一个服务,它向Bean注入@Autowired,如下所示 @Service public class AdminServiceImpl implements AdminService { @Autowired private WebServiceTemplate adminServiceTemplate; } 以及一个包含两个bean的xml,这会导致不明确的自动连接 <bean id="serviceWebClient" class="org.springframe
@Service
public class AdminServiceImpl implements AdminService {
@Autowired
private WebServiceTemplate adminServiceTemplate;
}
以及一个包含两个bean的xml,这会导致不明确的自动连接
<bean id="serviceWebClient" class="org.springframework.ws.client.core.WebServiceTemplate" scope="prototype">
<constructor-arg ref="messageFactory" />
<property name="marshaller" ref="marshaller" />
<!-- More properties -->
</bean>
<bean id="adminServiceWebClient" class="org.springframework.ws.client.core.WebServiceTemplate" scope="prototype">
<constructor-arg ref="messageFactory" />
<property name="marshaller" ref="marshaller" />
<!-- More properties -->
</bean>
奇怪的是:
当我在服务中添加@Qualifier来指定要选择的Bean时,它突然找不到了。例如,我将我的服务编辑为以下内容:
@Service
public class AdminServiceImpl implements AdminService {
@Autowired
@Qualifier("adminServiceWebClient")
private WebServiceTemplate adminServiceTemplate;
}
以后当我用context=new ClassPathXmlApplicationContextCONFIG\u FILE;检索ApplicationContext时,我没有得到指定的Bean,而是得到以下异常消息:
对这种奇怪的事情有什么合乎逻辑的解释吗?我甚至不知道从哪里开始调试。它似乎找到了两者,但仍然拒绝自动连接一个
编辑
从我的XML和@Qualifier注释中删除额外的Bean时,我仍然得到:
但它在启动时运行良好。它只是在调用以下命令后失败:
context = new ClassPathXmlApplicationContext(CONFIG_FILE);
因此,在启动时,它似乎发现它是必需的,并且没有失败,但在请求上下文时失败。也许您实际上启动了两个应用程序上下文?一个会有这些豆子,而另一个不会 如果是这种情况,当限定符出现时,第一个上下文将正常启动,但第二个上下文将失败,因为bean缺少异常2。如果没有限定符,第一个上下文将由于两个替代项而无法启动 要在启动第二个上下文时解决此问题,请为其提供一个父上下文:
new ClassPathXmlApplicationContext(new String[]{CONFIG_LOCATION}, parentContext);
我已经找到了这个问题发生的原因。这是一个相当愚蠢的错误。如果其他人也遇到这种情况,请查看以下内容:
@Service
public class AdminServiceImpl implements AdminService {
@Autowired
@Qualifier("adminServiceWebClient")
private WebServiceTemplate adminServiceTemplate;
}
概述
我使用各种Springbean文件运行我的应用程序。当我的应用程序启动时,我使用一个主上下文文件对整个基本包进行组件扫描。在这个主文件中,我有WebServiceTemplatebean
启动
我的组件扫描找到了我的服务,并将其尊敬的WebServiceTemplatebean自动连接到其中。因此,正如预期的那样,它在启动时运行良好
运行时
当我打电话时
context = new ClassPathXmlApplicationContext(CONFIG_FILE);
我实际上调用了另一个文件。此文件不包含WebServiceTemplate bean,但也包含对整个基本包的组件扫描。使它找到我的服务,但不是它应该自动连接的bean
解决方案
加载另一个文件时,我更改了组件扫描,使其更窄,以满足我的需要。因此,它不会扫描服务,但会在启动时加载。WebServiceTemplate是否实现接口?@dambros它实现WebServiceOperations,但它是一个Spring维护的类,用于发送SOAP消息。正常情况下,这没什么大不了的。不幸的是,我不能在这里复制这个问题。我试过使用Spring boot,但只要我添加了限定符,它就起作用了。这个答案对你有帮助吗。您可能使用了错误的autowire候选解析程序。这实际上是我的问题,当您发布此消息时,我正在写我的答案。谢谢你的帮助+1.
new ClassPathXmlApplicationContext(new String[]{CONFIG_LOCATION}, parentContext);
context = new ClassPathXmlApplicationContext(CONFIG_FILE);