Running Code on Spring Boot Startup

Running Code on Spring Boot Startup

On of the things I love about the Grails environment is that it comes with a handy bootstrap.groovy file. This will run at startup of the Spring container. I frequently use this to setup expected data, or to create test data for integration / functional tests. It can be a very convenient way to seed a H2 database with startup values.

The Spring Framework itself does not have the concept for a bootstrap file like Grails does. It does however have events that we can subscribe to and functionally accomplish the same thing.

Spring Framework Events

The Spring Framework comes out the of box with a number of events, and you’re able to extend the event functionality for your own purposes.

Spring Core Events

ContextRefreshedEvent

This event is published whenever the Spring Context is started or refreshed.

ContextStartedEvent

This event is published when the Spring Context is started.

ContextStoppedEvent

This event is published when the Spring Context is stopped. In practice you will not use this event very often. It can be handy for doing cleanup work, like closing connections.

ContextClosedEvent

This event is similar to the ContextStoppedEvent, but in this case the Context can not be re-started.

Spring Boot Events

Spring Boot introduces several new events on top of the events available in the core Spring Framework.

ApplicationStartedEvent

This event is published early in the startup of a Spring Application. The Spring Context is running, but may change later in the lifecycle.

ApplicationEnvironmentPreparedEvent

This event is published when the Spring Boot Application is starting up and is first available for inspection and modification.

ApplicationPreparedEvent

This event is published when the Spring Context is fully prepared but not refreshed. At this point the Spring Beans are loaded, configured and ready for use.

ApplicationFailedEvent

This event is published when the Spring Boot Application fails to start. This event is useful for error logging or alerting.

Using Spring Framework Events

Under the scenario we want to do something on startup we have two events we can consider using. Traditionally under Spring Framework, we can use the ContextRefreshedEvent. This event has been around since the beginning of the Spring Framework.

If you’re using Spring Boot, you do have additional events to select from. I often want to use a startup event to seed data for tests, so in this case, I need the database connection to be setup. Reading about the Spring Boot Events, I thought the event I would like to use is ApplicationPreparedEvent. But in testing it out, this was not the case. I ran into some issues with getting the event listeners setup properly in the Spring Boot Context. I found better results using the ContextRefreshedEvent.

ContextRefreshedEvent Listener

Here is an example of a listener. Here, I’m injecting a simple bean to prove I got a message. In practice this bean could be whatever you wanted. You could for example inject a Spring Data Repository into your listener bean.

2015-06-1217:24:47.158INFO14158---[main]g.s.b.c.ContextRefresehedApplication:Starting ContextRefresehedApplication on Johns-MacBook-Pro.local with PID14158(/Users/jt/src/springframework.guru/blogposts/target/classes started by jt in/Users/jt/src/springframework.guru/blogposts)

Testing the Spring Event Bean

I can also set this up in a JUnit test. This will actually run out side of Spring Boot and in a normal Spring context.

To do this I need to setup a simple Java configuration bean for my test.

ContextRefreshConfig.java

1

2

3

4

5

6

7

8

9

packageguru.springframework.blog.contextrefresh.config;

import org.springframework.context.annotation.ComponentScan;

import org.springframework.context.annotation.Configuration;

@Configuration

@ComponentScan("guru.springframework.blog.contextrefresh")

publicclassContextRefreshConfig{

}

ContextRefresehedListenerTest.java

Here I have a simple JUnit test which brings up the Spring Context, and gets an instance of the Event Holder Bean. I check to make sure the event fired is set to true, proving the bean did in fact get manipulated by the event listener.

Free Introduction to Spring Tutorial

Get The Code

I’ve committed the source code for this post to github. It is a Maven project which you can download and build. If you wish to learn more about the Spring Framework, I have a free introduction to Spring tutorial. You can sign up for this tutorial in the section below.

Source Code

The source code for this post is available on github. You can download it here.

jt

March 28, 2017 at 5:46 pm

I’d favor this approach, since its tapping into a context event. With the initializing bean, the framework may still be finalizing other beans. Might not matter, but I could see it leading to random failures.

Ravi Shankar

I have a question. Requesting your help.
We have a spring boot application and i have written integration tests without Mocks with TestRestTemplate and @SpringbootTest.

So on local machine, when i execute the tests, they execute fine as i have given MyApplication.class inside @Springboottest
It will startup the spring application context and execute the tests.

Till here everything is fine.

But we deploy this application on different test environments like qa,e2e,staging and then on production.
So we have to execute the Jenkins Job for my integration tests against the above environments as an acceptance tests.

My Question over here is : – When i execute these tests on jenkins, the tests get executed on a Jenkins Slave machine(which is picked randomly among the available executors) and it will hit the end points (either qa or e2e or staging or production end points) and send rest requests and get the responses and validate.
But the tests start up the application context on the jenkins slave and loads on a random port and will be available on the jenkins slave machine till the tests finish though i am not at all interacting with the application context( as i am hitting external test end points). Is there any option not to load the spring application context when i am trying to run tests against real test server and to load the application context when testing on local?