Home > maven, spring, spring-roo > Seed data for spring roo application.

Seed data for spring roo application.

When developing a spring roo application it can useful to have a mechanism, that creates test data on server startup, so that you have some data for manual testing.

Here I will describe how to accomplice that.

Make a class that implements ApplicationListener.

public class DataSeeder implements ApplicationListener {

    private final Log log = LogFactory.getLog(DataSeeder.class);

    public void onApplicationEvent(ContextRefreshedEvent event) {
        if (event.getApplicationContext().getParent() == null) { // root context
            log.info("event.getApplicationContext() = " + event.getApplicationContext());
            String runMode = "server";
            try {
                Resource resource = new ClassPathResource("/env.properties");
                Properties props = PropertiesLoaderUtils.loadProperties(resource);
                runMode = props.getProperty("run.mode");
            } catch (IOException ignored) {
            log.info("run.mode = " + runMode);
            if ("server".equals(runMode)) {
                // make seed data
                President president = new President();
                president.setName("Ron Paul");

The method onApplicationEvent is called once for each refreshed context. Since an application often has more than one context we must make sure that we only create seed data once. By checking if the context has a parent we can make sure that we only create seed data when the root context is refreshed.

Another issue is that we don’t want to create seed data when unit testing. So we have to find out if we are in test mode or on the server. In the test directory I made a properties file: test/resources/env.properties with one property:
, this properties file is only copied in the classpath during test. So if we can read its property we should not create seed data. That’s it.

  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: