我在我的 Web 应用程序端使用 Google Gson(gson) 库表单读取/写入 json 文件和 spring mvc 3。
所以在 Controller 中,我想创建一个带有 pretty-print 的 Gson 单例实例。在java中,代码是,
Gson gson = new GsonBuilder().setPrettyPrinting().create();
在 Controller 中,我创建了一个如下所示的 Autowiring 条目,
@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 的方法。我对 Spring 很陌生。谁能告诉我,是否可以用xml bean方法解决这个问题?
最佳答案
只需使用 in the documentation 所述的静态工厂方法即可并使用 Java 代码创建 Java 对象:它非常简单和安全:
<bean id="gson"
class="com.foo.bar.MyGsonFactory"
factory-method="create"/>
在 MyGsonFactory 中:
public static Gson create() {
return new GsonBuilder().setPrettyPrinting().create();
}
关于java builder模式对象的spring bean创建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29719334/