java builder模式对象的spring bean创建

标签 spring spring-mvc gson

我在我的 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/

相关文章:

java - 带有嵌套字段的Spring数据查询(连接其他列)

java - Eclipse:安装失败并出现错误

java - Spring计划的cron在3 :00 to 6:30之间

java - 处理巨大 Json Http 请求的最佳方法

java - Android:使用 Gson 解析 JSON 文件时出错

Java 将 JSON 字符串解析为数组或对象列表

java - 如何使用 Spring-Data JPA 保存数百万条记录

java - Spring 集成: Getting Exception on refreshing application context 2nd time

javax.validation.ConstraintViolationException : validation failed for classes during update time for groups

java - 基于 java 的配置中基于 spring xml 的配置