Spring:使用两个参数setter配置Bean [英] Spring: Configuring Bean with a two argument setter

查看:252
本文介绍了Spring:使用两个参数setter配置Bean的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用spring setter注入配置一个HttpParams,但HttpParams有一个两个参数setter(setParameter(String name,Object object))。有人知道在春天配置这个方法吗?

I would like to configure a HttpParams using spring setter injection but HttpParams has a two argument setter ( setParameter(String name, Object object) ). Is anyone aware of a way to configure this in spring?

我能想到的最接近的就像你做List,Set或Property配置:

The closest I can think of is like you would do a List, Set, or Property configuration:

http:/ /www.mkyong.com/spring/spring-collections-list-set-map-and-properties-example/

谢谢!

推荐答案

严格来说:具有两个参数的setter不是setter。
它违反了Java生成的JavaBeans约定。没有简单的方法来解决这个问题。

Strictly speaking: A setter with two parameters is not a setter. It violates the JavaBeans convention, on which Spring builds. There is no simple way to solve that.

另外,这里有一个Helper类可以用来配置你的HttpParam对象与Spring:

As an alternative, here's a Helper class you can use to configure your HttpParams object with Spring:

public class HttpParamSetter{

    private HttpParams httpParams;

    public void setHttpParams(HttpParams httpParams){
        this.httpParams = httpParams;
    }

    private Map<String, Object> parameters;

    public void setParameters(Map<String, Object> parameters){
        this.parameters = parameters;
    }

    @PostConstruct
    public void applyParameters(){
        for(Entry<String, Object> entry:parameters.entrySet()){
            httpParams.setParameter(entry.getKey(), entry.getValue());
        }

    }

}

这样连接:

<bean class="com.yourcompany.HttpParamSetter">
    <property name="httpParams" ref="httpParams" />
    <property name="parameters">
        <map>
            <entry key="foo" value="bar" />
            <entry key="baz" value="phleem" />
        </map>
    </property>
</bean>

这篇关于Spring:使用两个参数setter配置Bean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆