Convert Spring XML-based to Java-Based Configuration

12,240

Solution 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;
}

Solution 2

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

Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setClassesToBeBound(User.class);
Share:
12,240
xyzxyz442
Author by

xyzxyz442

Updated on June 10, 2022

Comments

  • xyzxyz442
    xyzxyz442 almost 2 years

    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.