All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.sixpointsix.springboot.datafixture.DataFixtureConfiguration Maven / Gradle / Ivy

There is a newer version: 1.2.0
Show newest version
package net.sixpointsix.springboot.datafixture;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import net.sixpointsix.springboot.datafixture.dummy.DummyDataFixture;
import net.sixpointsix.springboot.datafixture.runner.BasicDataFixtureRunner;
import net.sixpointsix.springboot.datafixture.runner.DataFixtureRunner;
import net.sixpointsix.springboot.datafixture.runner.NullDataFixtureRunner;

import java.util.Comparator;
import java.util.List;

@Configuration
@EnableConfigurationProperties(DataFixtureProperties.class)
public class DataFixtureConfiguration {

    @Autowired
    private DataFixtureProperties properties;

    @Bean
    @ConditionalOnMissingBean
    public DataFixtureRunner getDataFixtureRunner(DataFixtureList dataFixtureList) {
        if(!properties.isEnabled()) {
            return new NullDataFixtureRunner();
        }

        return new BasicDataFixtureRunner(dataFixtureList);
    }

    @Bean
    @ConditionalOnMissingBean
    public DataFixtureList getDataFixtureList(
            List initializerList,
            List fixtureFunctionSets) {
        fixtureFunctionSets
                .stream()
                .map(FixtureFunctionSet::asDataFixtures)
                .forEach(initializerList::addAll);

        initializerList.sort(Comparator.comparingInt(DataFixture::getOrder));

        return new DataFixtureList(initializerList);
    }

    /**
     * Default bean if needed
     * @return Default bean
     */
    @Bean
    @ConditionalOnMissingBean
    public DataFixture defaultInitializer() {
        return new DummyDataFixture();
    }

    /**
     * Default bean if needed
     * @return Default fixture
     */
    @Bean
    @ConditionalOnMissingBean
    public FixtureFunctionSet defaultFixtureFunctionSet() {
        return FixtureFunctionSet
                .builder()
                .setRun(o -> {})
                .setShouldApply(o -> false)
                .build();
    }

    @Bean(name = "dataInitializerSpringRunner")
    @ConditionalOnBean(DataFixtureRunner.class)
    public ApplicationRunner enableSpringRunners(DataFixtureRunner runner) {
        return args -> runner.runAll();
    }
}