当前位置: 首页 > 面试题库 >

将基于XML的Spring转换为基于Java的配置

翟渝
2023-03-14
问题内容

我尝试不使用任何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);
}

错误:投放问题。

先感谢您。


问题答案:
@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;
}


 类似资料: