@Autowired marks a constructor, field, or method as a dependency-injection point. The Spring container supplies the matching parameters or dependency when it creates and manages the surrounding component. Constructor injection makes the dependency explicit and supports a final field. section 12.2.1
Listing 12.6 NewLoanApplicationProcessor declaration and constructor
@Component #1
public class NewLoanApplicationProcessor {
@Value("${accepted.loans.topic}") #2
private String acceptedLoansTopic;
@Value("${rejected.loans.topic}")
private String rejectedLoansTopic;
@Value("${qa.application.topic}")
private String qaLoansTopic;
private final KafkaTemplate<String, LoanApplication>
kafkaTemplate; #3
@Autowired #4
public NewLoanApplicationProcessor(
KafkaTemplate<String, LoanApplication> kafkaTemplate) {
this.kafkaTemplate = kafkaTemplate;
}
A loan processor receives its KafkaTemplate through an annotated constructor, then uses that dependency to publish processed applications to output topics. section 12.2.1
Choose the annotation placement to match the managed object and lifecycle:
- Annotate a constructor to request dependencies needed to create the component, such as KafkaTemplate<String, LoanApplication>. section 12.2.1
- Use field-level autowiring when needed; the dependency can be injected directly into a field. section 12.2.1
- Annotate a method to receive a container-managed object while configuring work, such as a StreamsBuilder used to define a Kafka Streams topology. section 12.3
Injecting a managed StreamsBuilder
A topology method can accept StreamsBuilder through @Autowired rather than construct it itself. Spring passes the singleton builder to annotated methods and later builds it when the KafkaStreams instance starts. This lets topology declarations be distributed across classes, although keeping one topology together is recommended for easier debugging. section 12.3
Autowired injection is distinct from Kafka listener wiring. @KafkaListener causes a listener container and underlying consumer to be created for subscribed topics; an injected KafkaTemplate is instead a dependency used by application code to send records. Keep topic names and group IDs in properties when they may change. section 12.2.1
Letting Spring manage a StreamsBuilder reduces startup and configuration work, but hides some application behavior. For cases requiring direct lifecycle control, inject configuration into a topology class, explicitly create and build a StreamsBuilder, then create, start, and close KafkaStreams yourself. section 12.3
