【问题标题】:How setter works inside Spring Framework #2?setter 如何在 Spring Framework #2 中工作?
【发布时间】:2019-03-28 06:07:50
【问题描述】:

很抱歉复制了这个article。我想评论它,但没有 50 分的声誉我无法评论,所以......

我有

private boolean stopLoggingIntoDb;
....
  public void setStopLoggingIntoDb(String stopLoggingIntoDb) {  
    this.stopLoggingIntoDb = BooleanUtils.toBoolean(stopLoggingIntoDb.replaceAll("[^A-Za-z]", ""));
    logger.warn("Logging into SiebelMethodLogs is " + (!this.stopLoggingIntoDb ? "ON" : "OFF"));
}

和 XML

<bean id="siebelMethodProcessor" class="com.entities.utils.Logger">
    <property name="logService" ref="logService"/>
    <property name="stopLoggingIntoDb" value="${monitor.siebel.stopLogging}"/>
</bean>

在这种情况下,一切正常,但是如果我将 setter 方法中的属性从 stopLoggingIntoDb 更改为 stopLog 并将 XML 中的属性名称也更改为 stopLog,Spring 说我无效属性“stopLoggingIntoDb”或 Bean 属性“stopLog” ' 不可写。

因此,我的问题是 Spring 对 setter 方法做了什么?注入哪个值,在获取注入时搜索哪个字段/属性?

【问题讨论】:

  • 你能把修改后的代码也贴出来吗?

标签: java spring


【解决方案1】:

Spring Documentation 的这个例子中可以看出,&lt;property&gt; 元素的name 属性必须匹配一个setter 方法。方法参数的名称和字段的名称无关紧要。

依赖注入示例

以下示例将基于 XML 的配置元数据用于基于 setter 的 DI。 Spring XML 配置文件的一小部分指定了一些 bean 定义:

<bean id="exampleBean" class="examples.ExampleBean">
    <!-- setter injection using the nested ref element -->
    <property name="beanOne">
        <ref bean="anotherExampleBean"/>
    </property>

    <!-- setter injection using the neater ref attribute -->
    <property name="beanTwo" ref="yetAnotherBean"/>
    <property name="integerProperty" value="1"/>
</bean>

<bean id="anotherExampleBean" class="examples.AnotherBean"/>
<bean id="yetAnotherBean" class="examples.YetAnotherBean"/>
public class ExampleBean {

    private AnotherBean beanOne;
    private YetAnotherBean beanTwo;
    private int i;

    public void setBeanOne(AnotherBean beanOne) {
        this.beanOne = beanOne;
    }

    public void setBeanTwo(YetAnotherBean beanTwo) {
        this.beanTwo = beanTwo;
    }

    public void setIntegerProperty(int i) {
        this.i = i;
    }

}

请注意name="integerProperty" 如何匹配setIntegerProperty() 方法,即使参数名为i 且字段名为i

【讨论】:

  • Spring 是如何定义 setter 的?如果我在 Xml INTEGERproPERTY 中命名属性,那么,哪个 setter 应该在 Bean 内?没关系,每次都会设置(一些以大写字母开头的属性名称)?并且,对于我的示例,它将是 setINTEGERproPERTY 或 setIntegerProperty ?
  • @Dred 使用JavaBean naming convention,即以set开头的方法名,只有一个参数,属性名是set后面的文字,第一个字母小写,属性类型是参数的类型。所以如果你把方法命名为setINTEGERproPErTY,属性名就是iNTEGERproPErTY
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-05-15
  • 1970-01-01
  • 2013-03-25
  • 2013-11-12
  • 1970-01-01
  • 2022-11-05
  • 2018-05-03
相关资源
最近更新 更多