简体   繁体   中英

Injecting beans into a HttpMessageConverter in Spring Framework 3.1

I am trying to inject a bean into a custom HttpMessageConverter which is registered in a configuration class:

package my.package.config;

import ...

@Configuration
@ComponentScan( basePackages = "my.package" )
public class CompleteConfiguration extends WebMvcConfigurationSupport {

    @Override
    protected void configureMessageConverters( List<HttpMessageConverter<?>> converters ) {
        converters.add( this.myMessageConverter() );
        this.addDefaultHttpMessageConverters( converters );
    }

    @Bean
    public MyMessageConverter myMessageConverter() {
        MyMessageConverter mc = new MyMessageConverter();
        mc.setServiceDao( this.serviceDao() );
        return mc;
    }

    @Bean
    public ServiceDao serviceDao() {
        return ...;
    }

}

The custom HttpMessageConverter is defined as follows:

package my.package.converter;

public class MyMessageConverter implements HttpMessageConverter<Person> {

    private ServiceDao serviceDao;

    ...
    implementation which uses ServiceDao
    ...

    public void setServiceDao( ServiceDao s ) {
        this.serviceDao = s;
    }

    public ServiceDao getServiceDao() {
        return this.serviceDao;
    }
}

This doesn't work as intended, because Spring internally creates a new instance of MyMessageConverter , not setting the ServiceDao for this new instance.

I tried to

  • annotate MyMessageConverter#setServiceDao( ServiceDao s ) with @Autowired .
  • implement BeanFactoryAware in MyMessageConverter .

Both approaches didn't work. The MyMessageConverter object which is used to convert the HTTP message always ends up having a null reference stored in MyMessageConverter#serviceDao .

Neither Google nor the Spring Framework 3.1 documentation came up with information on that problem.

@Bob Flannigon: This is definitely not the problem. CompleteConfiguration#myMessageConverter() returns a correctely cofigured message converter. However, when I remove the zero-args constructor from MyMessageConverter , Spring throws the following exception:

org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [my.package.converter.MyMessageConverter]: No default constructor found; nested exception is java.lang.NoSuchMethodException: my.package.converter.MyMessageConverter.<init>()

I guess this means that Spring creates a new instance which is then used instead of my configured bean.

The behaviour vanishes after upgrading from Spring Framework 3.1.0 to Spring Framework 3.2.3.

Maybe it was just a bug.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM