我是一个 Spring 新手,有一个看似简单的 Spring 问题。我为此工作了几个小时,但运气不佳。这是异常,后面是代码(提前致谢):
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'graphiteWriterSession' defined in file [/home/user/resources/jmxtrans.graphite.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'host' of bean class [com.example.ExampleClass]: Bean property 'host' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
我的 bean 定义:
<bean id="graphiteWriterSession" class="com.example.ExampleClass">
<property name="host" value="host.example.com" />
<property name="port" value="2023" />
<property name="namespacePrefix" value="apps.foo.bar" />
<property name="debug" value="true" />
</bean>
<bean id="jmxtransSession" class="com.example.MainMethodClass" factory-method="getInstance">
<property name="graphiteWriterSession" ref="graphiteWriterSession" />
</bean>
代码片段:
package com.example.ExampleClass;
import com.googlecode.jmxtrans.model.output.GraphiteWriter;
public class ExampleClass {
private static final long serialVersionUID = 1L;
private String host;
private int port;
private GraphiteWriter gw;
public ExampleClass() {
}
public GraphiteWriter getWriter() {
gw = new GraphiteWriter();
gw.addSetting(GraphiteWriter.PORT, port);
gw.addSetting(GraphiteWriter.HOST, host);
return gw;
}
// =====================================================
// set/get methods for Carbon host.
// Plugged into Spring application-context file.
// =====================================================
public void setCarbonHost( String host ) {
this.host = host;
}
public String getCarbonHost() {
return host;
}
// =====================================================
// =====================================================
// set/get methods for Carbon port.
// Plugged into Spring application-context file.
// =====================================================
public void setCarbonPort( int port ) {
this.port = port;
}
public int getCarbonPort() {
return port;
}
// =====================================================
}
我没有在此处包含驱动程序(包含主要方法)类。虽然那个驱动类依赖于上面的类,但是驱动类本身没有问题(我不信)。
上面的错误显示“主机”属性有问题,但正如您所料,“端口”属性也有同样的问题(碰巧首先评估“主机”属性)。
谁能告诉我哪里出错了?如果您愿意,请随意解释,因为我本身不是 Spring 人员。谢谢。
最佳答案
1) 对于主机,您应该定义 public getHost()
和 setHost(String s)
方法,同样对于端口,您需要 getPort()
和 setPort(int v)
方法。
这是 Spring 初始化 bean 所需要的。
我认为它特别需要 setter(在这种情况下)。
或者……
2) 您可以将 XML 文件中的属性重命名为
carbonHost
和 carbonPort
。这也应该这样做。
关于java - Spring Bean 属性 'xxx' 不可写或具有无效的 setter 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21613703/