用于java构建器模式对象的spring bean创建

app*_*ppu 3 spring spring-mvc gson

我在我的Web应用程序端使用Google Gson(gson)库形式读/写json文件和spring mvc 3.

所以在控制器中,我想用漂亮的打印创建一个Gson的单例实例.在java中代码是,

Gson gson = new GsonBuilder().setPrettyPrinting().create();
Run Code Online (Sandbox Code Playgroud)

在Controller中,我创建了一个自动连接的条目,如下所示,

@Autowired
private Gson gson;
Run Code Online (Sandbox Code Playgroud)

和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"/>
Run Code Online (Sandbox Code Playgroud)

它会在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)
Run Code Online (Sandbox Code Playgroud)

我知道setPrettyPrinting()的setter签名与spring期望的不同,这就是spring抛出异常的原因.

  public GsonBuilder setPrettyPrinting() {
    prettyPrinting = true;
    return this;
  }
Run Code Online (Sandbox Code Playgroud)

但我无法找到一种方法来连接构建器模式bean.春天我很陌生.任何人都可以告诉我,是否有可能在xml bean方法中解决这个问题?

JB *_*zet 6

只需使用文档中描述的静态工厂方法,并使用Java代码创建Java对象:它更容易和安全:

<bean id="gson"
      class="com.foo.bar.MyGsonFactory"
      factory-method="create"/>
Run Code Online (Sandbox Code Playgroud)

在MyGsonFactory中:

public static Gson create() {
    return new GsonBuilder().setPrettyPrinting().create();
}
Run Code Online (Sandbox Code Playgroud)