Home > Blockchain >  Java - Proper Way To Initialize an Autowired Service
Java - Proper Way To Initialize an Autowired Service

Time:11-18

I have inherited a springboot application. This application has a service similar to the following:

@Service
public class MyService {
String param1 = "";
String param2 = "";

    public void doStuff() {
        // do stuff assuming the parameters param1 and param 2 of this autowired service have already been initialized
   }
}

, This service is autowired from another service similar to the following;

@Service
public MainService {

@Autowired MyService myService;

    public performWork() {

       this.myService.doStuff();
    }
}

, and finally, the springboot app is similar to the following. The calling of the listen() method happens once the Kafka topic has a message (Kafka is only here relevant here because it kicks off the calling of the autowired services):

@SpringBootApplication
public class MyApplication {

@Autowired
MainService mainService;

    public static void main(String[] args) {

            SpringApplication.run(MyApplication.class, args);
    }


    @KafkaListener(topics = "myTopic")
    public void listen(String message) {

        this.graphicService.performWork();

     }
}

Here is my question: What is a proper way to have the parameters param1 and param2 already initialized on the MyService service before its doStuff() method is called?

I would instead NOT use a bean configuration file, but rather have it performed as part of the starting of the springboot app. Any advice is appreciated. Thanks

CodePudding user response:

Per my understanding, you just want to execute initialization statements at your bean's initialization. You can use PostConstruct annotation for any work you need to do as soon as beans are created.

MyService class should look like the following

@Service
public class MyService {

    String param1;
    String param2;

    @PostConstruct
    public void postConstructRoutine() {
        // initialize parameters
        param1 = "some_value";
        param2 = "some_other_value";
    }

    public void doStuff() {
        // do stuff
   }

}

The PostConstruct annotation is used on a method that needs to be executed after dependency injection is done to perform any initialization.

You can find more info about the annotation at the documentation.

As a side note, it is always better to use constructor injection instead of Autowired. I would highly recommend it.

  • Related