Search code examples
javaspringspring-annotations

After bean definition created from @Configuration


The problem:

I have a bean (ConversionService) that needs a collection of Converters to be created. So within my @Configuration class I have a @Bean that is a Collection<Converter> with a specific @Qualifier.

For my ConversionService @Bean, I receive the Converter collection as parameter using my @Qualifier like this:

@Bean
public ConversionService createConversionService(@Qualifier("converters") converters) {
    // here I perform the ConversionService creation
}

This works and is exactly how I want it. But I have several @Configuration classes, and each one shall be able to add something to the Converter collection. I initially though maybe there is a way to implement a method invoked after bean definition is read from @Configuration class. Something like this:

@Configuration
public class MyConfiguration {

    @Autowired
    @Qualifier("converters")
    private Collection<Converter> converters;

    public void init() {
        converters.add(xy);
    }

}

or even

@Configuration
public class MyConfiguration {

    public void init(@Qualifier("converters") Collection<Converter> converters) {
        converters.add(xy);
    }

}

Solution

  • You should be able to add something to your converters in your @Configuration annotated class using the @PostConstruct annotation.

    @Configuration
    public class MyConfiguration {
    
        @Autowired
        @Qualifier("converters")
        private Collection<Converter> converters;
    
        @PostConstruct
        public void init() {
            converters.add(xy);
        }
    
    }