很抱歉收到此 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 方法做什么?注入(inject)哪个值以及在获取注入(inject)时搜索哪个字段/属性?
最佳答案
正如 Spring Documentation 中的示例所示,name
<property>
的属性元素必须与 setter 方法匹配。方法参数的名称和字段的名称并不重要。
Examples of dependency injection
The following example uses XML-based configuration metadata for setter-based DI. A small part of a Spring XML configuration file specifies some bean definitions:
<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
.
关于java - setter 在 Spring Framework #2 中如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55391113/