Cheyne's Blog


  • Home
  • Archive
  • Categories
  •    

© 2025 John Doe

Theme Typography by Makito

Proudly published with Hexo

A tip in Spring IOC

Posted at 2024-05-02 Coding Tips 

These days, I’m learning how Apache Kafka is used in Springboot. And I found an interesting tip in Springboot ioc.

Before, I injected the bean into another bean like this:

1
2
3
4
5
6
7
8
9
10
@Service
public class KafkaProducer {

private KafkaTemplate<String, String> kafkaTemplate;

@Autowired
public KafkaProducer(KafkaTemplate<String, String> kafkaTemplate) {
this.kafkaTemplate = kafkaTemplate;
}
}

Or like this:

1
2
3
4
5
6
@Service
public class KafkaProducer {

@Autowired
private KafkaTemplate<String, String> kafkaTemplate;
}

But, when I learned with this tutorial, the author inject the kafkaTemplate like this:

1
2
3
4
5
6
7
8
9
@Service
public class KafkaProducer {

private KafkaTemplate<String, String> kafkaTemplate;

public KafkaProducer(KafkaTemplate<String, String> kafkaTemplate) {
this.kafkaTemplate = kafkaTemplate;
}
}

In other words, this way of injecting without @Autowired, made me feel amazed.

He said Spring framework will automatically inject this dependency(kafkaTemplate) whenever this bean(KafkaProducer) has only one parameterized constructor. I think is a useful and elegant way.

Share 

 Previous post: AbstractFactory Next post: RabbitMQ Tutorials 

© 2025 John Doe

Theme Typography by Makito

Proudly published with Hexo