E
E
Evgeniy Rybalko2020-06-28 18:41:37
Java
Evgeniy Rybalko, 2020-06-28 18:41:37

How to properly load resources in Spring?

Good afternoon
I am writing an application in which at startup it is necessary that configuration files (properties + json) be pulled up.
Application services will constantly access this configuration and I don’t want to take it out separately to the database.
The idea is that configuration files are read at startup, configuration data can be obtained by calling the singleton method Question one: As I understand it, the logic for reading application settings at startup can be done using the InitializingBean Interface https://www.baeldung.com/running-setup -logic-on-st... In the same class, the received parameters are "added" to the singleton, which will be accessed by the services Question two Do I have the right approach to solving this problem?
MyConfig.getInstance().getValue("key")



Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Orkhan, 2020-06-29
@whereeaglesdare

Another simple solution -
Create an ApplicationProperties file

@Configuration
@ConfigurationProperties(prefix = "application")
public class AppProperties {

    @Getter
    @Setter
    private String baseUrl;

   
    @Getter
    @Setter
    private String uploadPath;

}

Add the required configs:
application.base_url=http://localhost:7777
application.upload_path=/home/admin/application.com/uploads

Pay attention to the parameter names.
First, specify the application prefix in the config (you can specify your own prefix).
Next base_url => baseUrl upload_path => uploadPath
Next, in MyApplication (at the entry point of the application), add the annotation:
@EnableConfigurationProperties({
        ApplicationProperties.class
})
public class MyApplication {
}

Now, in any Spring component, you can autowire this class and get the necessary parameters using getters.
Here, .example:
@Controller
@RequiredArgsConstructor
public class MyController {

private final ApplicationProperties properties;

// ... тут методы контроллера
String uploadPath = properties.getUploadPath();
//...

}

Source - https://www.baeldung.com/properties-with-spring

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question