Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Spring XML-based to Java-Based Configuration

I try not to using any 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>

like this one: convert to @Bean

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

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

    return restTemplate;
}

Problem here.

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

Try to convert "com.cloudlb.domain.User" into Class [] not thing work.

@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);
}

Error: problem with casting.

Thank you in advance.

like image 373
xyzxyz442 Avatar asked Jan 03 '12 20:01

xyzxyz442


2 Answers

@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;
}
like image 138
Tomasz Nurkiewicz Avatar answered Sep 29 '22 18:09

Tomasz Nurkiewicz


setClassesToBeBound takes a vararg list, so you can just do this:

Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setClassesToBeBound(User.class);
like image 32
skaffman Avatar answered Sep 29 '22 16:09

skaffman