应用程序上下文中的Java bean定义(Spring)

时间:2011-09-16 20:33:52

标签: java 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>

如果需要更多信息,请与我们联系。

3 个答案:

答案 0 :(得分:0)

<bean id="apacheHttpClient" class="com.sun.jersey.client.apache.ApacheHttpClient" 
         factory-method="getRestClient"/>

好像你几乎拥有它。它不工作吗?然后,您需要将此bean作为属性或构造函数arg传递给任何需要使用它的类。

答案 1 :(得分:0)

我想你想问的是如何告诉Spring使用静态工厂方法创建bean。

This thread可能有所帮助。

<bean id="restClient" class="com.your.app.ClassWithTheFactoryMethod" factory-method="getRestClient"/> </bean>

应该有效

答案 2 :(得分:0)

这是我最接近完全你在代码中所拥有的东西。我不得不从字面上引用ApacheHttpClientConfig.PROPERTY_CONNECT_TIMEOUT的值,并为RESTUtil.dispatcherHttpTimeOut输入120(因为我不知道它是什么)。请注意,需要“#{120}”表达式将该值作为Integer而不是String传递,这将导致异常。

<!-- 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>
相关问题