Reputation: 2749
In spring boot web application, is it possible to ensure some code is executed before the embedded webserver (tomcat) is listening for incoming requests?
I have some data base migration scripts that need to be run before any request from my REST API is responded by the application. How can I do that? For now, my migration script component uses @EventListener
for ContextRefreshedEvent
but that is too late. The following line is already logged before:
o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8091 (http) with context path ''
Upvotes: 2
Views: 851
Reputation: 2297
You can use @PostConstruct
method in the bean that you use to connect to the database (repository) and write there the code you need to run the scripts, this code is going to be executed after the bean is created but before the server is running.
Example: https://www.baeldung.com/spring-postconstruct-predestroy
Upvotes: 1
Reputation: 2749
I used the following approach finally:
@Component
public class MigrationLogic implements SmartInitializingSingleton {
@Override
@Transactional
public void afterSingletonsInstantiated() {
// run your logic here, declare dependencies with @Autowired
}
}
The SmartInitializingSingleton
executes before the web server is starting up.
Upvotes: 1