我在设置具有不明确 setter 方法的 bean 的属性时遇到问题。
问题是 HttpClient 的 hostConfiguration.host 属性有 3 种可能的使用方法:
- HostConfiguration.setHost(字符串主机)
- HostConfiguration.setHost(HttpHost 主机)
- HostConfiguration.setHost(URI 主机)
这是我的 bean 定义:
<bean id="primaryClient" class="org.apache.commons.httpclient.HttpClient">
<property name="hostConfiguration.host">
<bean class="org.apache.commons.httpclient.HttpHost" >
<constructor-arg value="somelink.com"/>
<constructor-arg value="443"/>
<constructor-arg>
<bean class="org.apache.commons.httpclient.protocol.Protocol">
<constructor-arg value="https"/>
<constructor-arg ref="sslProtocolSocketFactory"/>
<constructor-arg value="443"/>
</bean>
</constructor-arg>
</bean>
</property>
</bean>
这是堆栈:
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'primaryClient' defined in class path resource [spring/test-merchantlink-context.xml]: Error setting property values; nested exception is org.springframework.beans.PropertyBatchUpdateException; nested PropertyAccessExceptions (1) are: PropertyAccessException 1: org.springframework.beans.TypeMismatchException: Failed to convert property value of type [org.apache.commons.httpclient.HttpHost] to required type [java.lang.String] for property 'hostConfiguration.host'; nested exception is java.lang.IllegalArgumentException: Cannot convert value of type [org.apache.commons.httpclient.HttpHost] to required type [java.lang.String] for property 'host': no matching editors or conversion strategy found
我该如何解决这个问题?我正在使用 spring 2.5.6
最佳答案
基本上,重载 setter 违反了 JavaBeans 规范,因此不受 spring 支持。可以看到https://jira.spring.io/browse/SPR-4931了解更多详情。
由于您可能没有创建 HttpClient,因此无法更改它,因此一种解决方案是使用工厂 bean。这看起来像这样:
<bean id="httpClientFactory" class="my.package.HttpClientFactory"/>
<bean id="primaryClient" factory-bean="httpClientFactory" factory-method="create">
您可以在 my.package.HttpClientFactor
上实现 create()
方法来设置和返回您的工厂。
如果您想在 XML 配置中而不是在代码中设置特定参数,您可以将构造函数参数添加到 my.package.HttpClientFactor
。
关于java - 不明确的 setter 方法导致分配属性值出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25335302/