0

I have a small service on SpringBoot and Mongodb as a DB. I need to be able create a small collection with one document ( very basic: id, name, status) on startup. An analog of sql create table if not exists, but for mongo. How do I do that? I tried to initialize values in the document attributes, but it didn't help. Currently, collection and the document appear only if I use API to add it.

2 Answers 2

1

You may want to use something like ApplicationRunner or CommandLineRunner which can be defined as a bean.

Example:

@SpringBootApplication
public class MyApplication {

    public static void main(String[] args) {
        SpringApplication.run(MyApplication .class, args);
    }

    @Bean
    public CommandLineRunner initialize(MyRepository myRepository) {

        return args -> {
            // Insert elements into myRepository 
        };
    }
}

Both CommandLineRunner and ApplicationRunner are functional interfaces, so we can use a lambda for them. Spring Boot will execute them at the startup of the application.

Sign up to request clarification or add additional context in comments.

Comments

1

You can leverage the spring internal event mechanism. When your application is ready, spring triggers the event ApplicationReadyEvent

You can listen to this event and init your collection:

@Component
public class DataInit implements ApplicationListener<ApplicationReadyEvent> {

    private final MyRepository myRepository;

    public DataInit(MyRepository myRepository) {
        this.myRepository = myRepository;
    }

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        // init data
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.