[英]Java bean definition in application context (Spring)
我是Spring IOC的新手,如何在應用程序上下文xml中將該方法轉換為bean定義?
import com.sun.jersey.api.client.Client;
import com.sun.jersey.client.apache.ApacheHttpClient;
import com.sun.jersey.client.apache.config.ApacheHttpClientConfig;
import com.sun.jersey.client.apache.config.DefaultApacheHttpClientConfig;
public static Client getRestClient() {
// configuration for jersey client
ApacheHttpClientConfig config = new DefaultApacheHttpClientConfig();
Map<String, Object> properties = config.getProperties();
properties.put(ApacheHttpClientConfig.PROPERTY_CONNECT_TIMEOUT,
RESTUtil.dispatcherHttpTimeOut);
// create client
return ApacheHttpClient.create(config);
}
更詳細的信息:我想從Spring IOC獲取Client的實例,當前我使用此方法(getRestClient)來獲取它,因此如下所示:
<!-- Apache http rest client -->
<bean id="apacheHttpClient" name="Rest Client"
class="com.sun.jersey.client.apache.ApacheHttpClient" factory-method="create">
<constructor-arg></constructor-arg>
</bean>
請讓我知道是否需要更多信息。
<bean id="apacheHttpClient" class="com.sun.jersey.client.apache.ApacheHttpClient"
factory-method="getRestClient"/>
好像您幾乎擁有了它。 它不起作用嗎? 然后,您只需要將此bean作為ref作為屬性或構造函數arg傳遞給需要使用它的任何類。
我猜您想問的是如何告訴Spring使用靜態工廠方法創建bean。
該線程可能會有所幫助。
<bean id="restClient" class="com.your.app.ClassWithTheFactoryMethod" factory-method="getRestClient"/> </bean>
應該管用
這是我能來到這樣你在你的代碼有什么最接近的一次。 我必須從字面上引用ApacheHttpClientConfig.PROPERTY_CONNECT_TIMEOUT的值,並且僅將RESTUtil.dispatcherHttpTimeOut放入120(因為我不知道它是什么)。 請注意,需要使用“#{120}”表達式將其值作為整數而不是字符串傳遞,這將導致異常。
<!-- Apache http rest client -->
<bean id="apacheHttpClient" name="Rest Client"
class="com.sun.jersey.client.apache.ApacheHttpClient" factory-method="create">
<constructor-arg>
<bean class="com.sun.jersey.client.apache.config.DefaultApacheHttpClientConfig">
<property name="properties['com.sun.jersey.client.property.connectTimeout']" value="#{120}" />
</bean>
</constructor-arg>
</bean>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.