The correct way for creation of KafkaTemplate in spring boot

I had the same issue initially, but when I executed it gave no errors and worked fine.

Ignore Intellij IDEA's warning, it may be a IDEA's bug figuring out autowired components.


By default KafkaTemplate<Object, Object> is created by Spring Boot in KafkaAutoConfiguration class. Since Spring considers generic type information during dependency injection the default bean can't be autowired into KafkaTemplate<String, byte[]>.


I think you can safely ignore IDEA's warning; I have no problems wiring in Boot's template with different generic types...

@SpringBootApplication
public class So55280173Application {

    public static void main(String[] args) {
        SpringApplication.run(So55280173Application.class, args);
    }

    @Bean
    public ApplicationRunner runner(KafkaTemplate<String, String> template, Foo foo) {
        return args -> {
            template.send("so55280173", "foo");
            if (foo.template == template) {
                System.out.println("they are the same");
            }
        };
    }

    @Bean
    public NewTopic topic() {
        return new NewTopic("so55280173", 1, (short) 1);
    }

}

@Component
class Foo {

    final KafkaTemplate<String, String> template;

    @Autowired
    Foo(KafkaTemplate<String, String> template) {
        this.template = template;
    }

}

and

they are the same