Grim
Grim

Reputation: 1831

How to autowire dependency within a Spring Boot Converter?

I am struggling with a way to autowire a dependency within a converter class using spring boot. What is the most elegant solution to solve this problem?

Configuration

@Configuration
public class Config {

    @Bean
    public ConversionServiceFactoryBean conversionFacilitator() {
        ConversionServiceFactoryBean factory = new ConversionServiceFactoryBean();
        factory.setConverters(getConverters());
        return factory;
    }


    private Set<Converter> getConverters() {
        Set<Converter> converters = new HashSet<>();
        converters.add(new MyConverter());
        return converters;
    }
}

Converter class

@Component
public class MyConverter implements Converter<Type1, Type2> {

    @Autowired
    private Dependency dependency; // Null here due to the component not being injected


    @Override
    public Type2 convert(Type1 type1) {
        return dependency.something(type1);
    }
}

Upvotes: 0

Views: 881

Answers (1)

alfcope
alfcope

Reputation: 2427

The dependency is not being injected because you are creating MyConverter with new, instead of let Spring create it.

You do not need a method to return set of converters. Spring can do it for you, just auto wiring it. Spring is smart enough to give you a set with all the converter implementations it finds.

You should use something like:

@Configuration
public class Config {

  @Bean
  @Autowired
  public ConversionServiceFactoryBean conversionFacilitator(Set<Converter> converters) {
    ConversionServiceFactoryBean factory = new ConversionServiceFactoryBean();
    factory.setConverters(converters);
    return factory;
  }
}

Upvotes: 1

Related Questions