【问题标题】:Convert Spring XML-based to Java-Based Configuration将 Spring 基于 XML 的配置转换为基于 Java 的配置
【发布时间】:2012-02-01 19:56:07
【问题描述】:

我尽量不使用任何 xml。

<bean id="restTemplate" class="org.springframework.web.client.RestTemplate">

    <property name="messageConverters">
        <list>
            <bean class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter">
                <property name="marshaller" ref="jaxbMarshaller"/>
                <property name="unmarshaller" ref="jaxbMarshaller"/>
            </bean>
            <bean class="org.springframework.http.converter.FormHttpMessageConverter"/>
        </list>
    </property>
</bean>

喜欢这个:转换为@Bean

@Bean
public RestTemplate restTemplate() {
    RestTemplate restTemplate = new RestTemplate();
    List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>();

    converters.add(marshallingMessageConverter());
    restTemplate.setMessageConverters(converters);

    return restTemplate;
}

这里有问题。

<bean id="jaxbMarshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
    <property name="classesToBeBound">
        <list>
            <value>com.cloudlb.domain.User</value>
        </list>
    </property>
</bean>

尝试将“com.cloudlb.domain.User”转换为 Class [] 不起作用。

@Bean
public MarshallingHttpMessageConverter marshallingMessageConverter() {
    Jaxb2Marshaller marshaller = new Jaxb2Marshaller();

    //
    List<Class<?>> listClass = new ArrayList<Class<?>>();
    listClass.add(User.class);

    marshaller.setClassesToBeBound((Class<?>[])listClass.toArray());
    // --------------------------------

    return new MarshallingHttpMessageConverter(marshaller, marshaller);
}

错误:投射问题。

提前谢谢你。

【问题讨论】:

  • 发布您遇到的错误
  • 不应该将&lt;list&gt; 转换为List 而不是数组吗?
  • @Thomas: &lt;list&gt; 将被强制执行任何必要的操作,例如List,或数组。

标签: java xml spring configuration spring-annotations


【解决方案1】:
@Bean
public MarshallingHttpMessageConverter marshallingMessageConverter() {
    return new MarshallingHttpMessageConverter(
        jaxb2Marshaller(),
        jaxb2Marshaller()
    );
}

@Bean
public Jaxb2Marshaller jaxb2Marshaller() {
    Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
    marshaller.setClassesToBeBound(new Class[]{
               twitter.model.Statuses.class
    });
    return marshaller;
}

【讨论】:

    【解决方案2】:

    setClassesToBeBound 采用可变参数列表,因此您可以这样做:

    Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
    marshaller.setClassesToBeBound(User.class);
    

    【讨论】:

      猜你喜欢
      • 2014-09-25
      • 1970-01-01
      • 1970-01-01
      • 2013-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-15
      相关资源
      最近更新 更多