【发布时间】:2015-04-18 15:33:30
【问题描述】:
我在我的 Web 应用程序端使用 Google Gson(gson) 库表单读取/写入 json 文件和 spring mvc 3。
所以在控制器中,我想创建一个带有漂亮打印的 Gson 单例实例。在java中,代码是,
Gson gson = new GsonBuilder().setPrettyPrinting().create();
在 Controller 中,我创建了一个如下所示的自动装配条目,
@Autowired
private Gson gson;
xml bean配置如下,
<bean id="gsonBuilder" class="com.google.gson.GsonBuilder">
<property name="prettyPrinting" value="true"/>
</bean>
<bean id="gson" factory-bean="gsonBuilder" factory-method="create"/>
它在 catalina 日志中抛出以下异常,
Caused by: org.springframework.beans.NotWritablePropertyException: Invalid property 'prettyPrinting' of bean class [com.google.gson.GsonBuilder]: Bean property 'prettyPrinting' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
at org.springframework.beans.BeanWrapperImpl.setPropertyValue(BeanWrapperImpl.java:1024)
at org.springframework.beans.BeanWrapperImpl.setPropertyValue(BeanWrapperImpl.java:900)
at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:76)
at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:58)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1358)
我知道 setPrettyPrinting() 的 setter 签名与 spring 预期的不同,这就是 spring 抛出异常的原因。
public GsonBuilder setPrettyPrinting() {
prettyPrinting = true;
return this;
}
但我无法找到连接构建器模式 bean 的方法。我对春天很陌生。谁能告诉我,是否可以用xml bean方法解决这个问题?
【问题讨论】:
标签: spring spring-mvc gson