coderatchet
coderatchet

Reputation: 8420

injecting beans into spring java config classes

I have a configuration class which uses the @Configuration annotation and also extends the RepositoryRestMvcConfiguration.

as part of the extended class, there are overridable methods that allow configuration of the bean recipes. one of which is configuring the conversion services available to the spring component.

I would like to inject some beans into a list that is iterated over and added as a conversion service through this overrided method, My configuration java class is defined below:

@Configuration
@EnableJpaRepositories(basePackages = "com.example.model.repositories")
public class DataConfig extends RepositoryRestMvcConfiguration {

    List<Converter<?,?>> converters;
    //get
    //set

    @Override
    protected void configureConversionService(ConfigurableConversionService conversionService){
        for(Converter converter : converter){
            conversionService.addConverter(converter);
        }
    }
}

The following defines my converters that i wish to inject in the app-context.xml file

<beans>
    <bean id="fooToBarConverter" class="com.example.model.converters.FooToBarConverter" />
    <bean id="barToFooConverter" class="com.example.model.converters.BarToFooConverter" />

    <util:list id="myConverters" value-type="org.springframework.core.convert.converter.Converter">
        <ref bean="barToFooConverter"/>
        <ref bean="fooToBarConverter" />
    </util:list>
</beans>

Is there a better way of providing these converters through spring configuration or do i need to explicitly list them as output of a function contained within my configuration class like:

@Bean
public List<Converter<?,?> myConverters(){
    Arrays.asList(new FooToBarConverter(), new BarToFooConverter());
}

Your help is highly appreciated.

P.S. since you are so good at spring, would you mind having a look at my spring-data-rest-mvc related question? please and thank you.

Upvotes: 0

Views: 1984

Answers (1)

Stephane Nicoll
Stephane Nicoll

Reputation: 33091

By default, any @Autowired (or @Resource) annotated Collection (or List, Set, etc) of a certain type will contain all beans of that type discovered in the context. You could add an @Autowired in your setter and let Spring injects your controller for you.

If you need a more fine-grained control over which converters should be configured and which one should not, maybe you should configure the ConversionService altogether instead.

Upvotes: 1

Related Questions