1

In Spring Boot I have a class that I want to instantiate by passing parameters in the the constructor in runtime. I am able to do this but all of the AutoWire properties are null and PostConstruct doesn't get called.

Constructor<KafkaController> constructorsA[] = (Constructor<KafkaController>[]) KafkaController.class.getConstructors();
KafkaController kafkaObject = constructorsA[0].newInstance(new Object[] { "1", "2" });

This is the class in question

@Component
public class KafkaController {

private KafkaConsumer<String, String> consumer;

@Autowired
private Util sentinelUtil;

final String subscriberID;
final String interactionID;

@Autowired
public KafkaController(@Value("") String subscriberID, @Value("") String interactionID) {
    this.subscriberID = subscriberID;
    this.interactionID = interactionID;
}

@PostConstruct
private void initKafka() {

}

}

Do I have to instantiate the class using a different method?

Brian Kalski
  • 897
  • 9
  • 35
  • You are creating it out side of the spring context, spring does not know about any class that it doesn't instantiate. What exactly are you trying to achieve? There are a few methods of creating different instances of beans based of externalized properties. – Darren Forsythe Apr 23 '19 at 19:01
  • I want to pass two parameters to a class that will open a Kafka queue and bring back data based on the data passed in. – Brian Kalski Apr 23 '19 at 20:10

0 Answers0