Sunday, December 18, 2022

Loading Configuration along with SpringBoot main class

In situation where the service will not be triggered by a clients and need to start doing some action like reading files, reading streams,  reading data from Twitter, etc.,

when the applications starts we need to find a way to trigger the reading logic.

To do that, we have different options. 



Application YAML file is used to hold the application configuration properties.

Spring boot binds external properties from application.YAML or 

application.properties file into a application at runtime.


Multiple ways:

1) PostConstruct

2) ServeletContextListener

3) ApplicationListener

4) CommandListener


 1) Using PostConstruct

One way is that we can use post construct annotation on methods, let's say, with a method in it.




Now, the code we write here in the init method will be called once after the spring being created.

And by default, spring beans are created once because they are created a singleton.

However, we can actually change these behaviors with scope annotation.





Here we see the supported scope annotations for a bean definition in spring

For example, if you set it to TYPE  "request", it will create a new bean for each request.




So how many times the init method will be called FOR ABOVE SCOPE Then?  it will be called in each request separately because the method will run after each object creation. That means for each request.

So actually, this is not a good option for an application general initialization job.

Although this behavior is only valid, for example, for a controller, where a request will cause to create A NEW BEAN. 



2) another option which is implementing application listener interface and overriding onApplicationEvent method.

This is an application listener method, so it will only run once for sure.

Therefore, we can use it.

Here, the parameter is ApplicationEvent for these method



  

3) implementing commandLineRunner and overriding the run method.

This is also a perfect option for application initialization logic.

The only difference with the previous way is the parameters.

Here we have a string array as parameter in the previous method

The parameter was applicationEvent.





No comments:

Post a Comment