Archive

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.

@Component
public class DataSeeder implements ApplicationListener {

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

    @Override
    @Transactional
    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");
                president.persist();
            }
        }
    }
}

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:
run.mode=test
, 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.