Archive for the ‘spring’ Category

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
  "event.getApplicationContext() = " + event.getApplicationContext());
            String runMode = "server";
            try {
                Resource resource = new ClassPathResource("/");
                Properties props = PropertiesLoaderUtils.loadProperties(resource);
                runMode = props.getProperty("run.mode");
            } catch (IOException ignored) {
  "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/ 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.