可以改进以下Spring DI xml吗? xml下面是配置目标bean的编程方法。
<bean id="jacksonObjectMapper" class="org.codehaus.jackson.map.ObjectMapper" />
<bean id="jacksonSerializationConfig" class="org.codehaus.jackson.map.SerializationConfig"
factory-bean="jacksonObjectMapper" factory-method="getSerializationConfig" />
<bean
class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetObject" ref="jacksonSerializationConfig" />
<property name="targetMethod" value="setSerializationInclusion" />
<property name="arguments">
<list>
<value type="org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion">NON_NULL</value>
</list>
</property>
</bean>
ObjectMapper mapper = new ObjectMapper(); mapper.getSerializationConfig()setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
答案 0 :(得分:3)
XML是一种非常糟糕的方法。是的,您可以执行此操作,但编写用于FactoryBean
的{{1}}更容易:
ObjectMapper
然后在您的XML中:
public class MyObjectMapperFactoryBean extends AbstractFactoryBean<ObjectMapper> {
public Class<ObjectMapper> getObjectType() {
return ObjectMapper.class;
}
public ObjectMapper createInstance() {
// create and return ObjectMapper
}
}
答案 1 :(得分:1)
仍然不完全理想,但有点清洁:
<bean id="objectMapperBuilder1" class="org.codehaus.jackson.map.ObjectMapper"/>
<bean id="objectMapperBuilder2" factory-bean="objectMapperBuilder1" factory-method="setSerializationInclusion">
<constructor-arg value="NON_NULL"/>
</bean>
<bean id="jsonWriter" factory-bean="objectMapperBuilder2" factory-method="writerWithDefaultPrettyPrinter" />
<!-- etc, etc -->
一个缺点是你将在内存中有不必要的bean实例。 (我正在使用这种方法,我将继续使用它,直到Spring决定处理这些方法)。这里和Spring论坛上有很多主题,要求像杰克逊使用的构建器模式一样支持流利的设置器,但在那之前你必须为你选择较小的邪恶。
答案 2 :(得分:1)
我同意@skaffman使用FactoryBean代替不可避免的复杂Spring XML bean配置来配置Jackson ObjectMapper的一般方法。 Spring 3.2+现在提供了开箱即用的FactoryBean。请参阅JacksonObjectMapperFactoryBean / Jackson2ObjectMapperFactoryBean。以下是通过Spring FactoryBean配置ObjectMapper的Spring XML示例 -
<bean id="jacksonObjectMapper" factory-bean="&jacksonObjectMapperFactoryBean" factory-method="getObject"/>
<bean id="jacksonObjectMapperFactoryBean" class="org.springframework.http.converter.json.JacksonObjectMapperFactoryBean">
<property name="featuresToDisable">
<array>
<util:constant static-field="org.codehaus.jackson.map.SerializationConfig$Feature.WRITE_NULL_PROPERTIES"/>
</array>
</property>
</bean>
(注意需要在'factory-bean'属性中使用&amp; amp来指示Spring在FactoryBean本身使用工厂方法,而不是它创建的bean。)