Search code examples
springspring-mvcspring-bootspring-annotations

Spring initialise test data in order


In my Spring application I am using the annotation @PostConstruct to initialise test data when the Spring application starts to run.

I have two classes CInitialiser and PInitialiser due to the nature of how I have setup the project i need the PInitialiser class to run first. The relationship between the two entities is a bidirectional many to many.

I need the PInitialiser entity to run first because I need to initlaise the projects to assign them to customers. But it looks like CInitialiser is running first. Is there anyway to make the entity Project run first?

Here is my code:

@PostConstruct
public void init() {
    for (Module m : modules) {
        if (enviromentTest) {
            try {
                m.initData();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

and each of my classes implements the Module:

public class CInitialiser implements Module

public class PInitialiser implements Module


Solution

  • You can specify the order in which spring beans are initialized using @Order annotation. docs Here are some examples

    What is the use of @Order annotation in Spring?

    https://javapapers.com/spring/spring-order-annotation/