多个RestTemplate和CredentialProviders在Spring中运行不佳

时间:2013-10-04 21:52:42

标签: apache-httpclient-4.x resttemplate

我有一个使用RestTemplate和CreditialProvider的应用程序完全按照此StackOverflow条目(RestTemplate with Basic Auth in Spring 3.1)的接受解决方案中描述的方式。

当我使用此设置单个服务时,这工作得很好。 但是我最近添加了一个新的RestTemplate供另一个服务使用,具有不同的用户名和密码,并且在其生命周期内无法使用用户名和密码来生成Rest请求。所有bean id都不同,因此不存在任何问题。

当单步执行Spring启动时,它似乎只是将一组空的凭据附加到HttpClient。

使用此解决方案时我应该考虑的任何建议或陷阱?什么单身(池)导致弄乱这个解决方案?

1 个答案:

答案 0 :(得分:0)

好吧,我终于明白了。这是一个春天的事情,是那些很难找到的令人烦恼的事情之一。

问题的核心是我的问题中提到的解决方案的这一部分:

<!-- Used to invoke a method in BasicCredentialsProvider.  This has to be done this way as BasicCredentialsProvider does not take 
provider and credentials in constructor or setter method.  It has to set by invoking setCredentials() method and passing two arguments -->  
<bean id="methodInvoke" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
    <property name="targetObject"><ref local="credentialProvider" /> </property>
    <property name="targetMethod" value="setCredentials"> </property>
    <property name="arguments"  >
        <list>
            <ref local="authScope" />
            <ref local="credentials" />
        </list>
    </property>
</bean>

为我的Rest服务创建第二组Spring定义时,我复制并粘贴,没有意识到“methodInvoke”的重复id值会导致只运行一次。

底线:如果不需要一个bean,就不要给它一个id - 它只会给你一个悲伤。在这种情况下,它不会在其他任何地方引用,因为它只是一个MethodInvoker。