Spring Boot: Initially data parsing

user2170547 :

I am searching for a way to read and parse a lot of data when the spring boot app is starting and be able to use these data later in other classes.

I started with a class DataRepository.java and annotated it with @Service to be able to inject it later. I'm planning to read the data here and to inject it in any other class I need the data.

But how can I achieve to parse the data just once and at app startup? The spring boot app should only be reachable if the parsing is done.

Max Farsikov :

Your approach with @Service is 100% appropriate.

By default all beans are singletons, so if you parse data on bean creation (in constructor) it will be parsed only once, and this info can be used in other beans by simple injection.

Please note that if during data parsing you have to use other beans, you should be confident that all beans are completely constructed. For that you should use approach proposed by @jreznot: https://stackoverflow.com/a/51783858/5289288

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=113457&siteId=1