Java 在应用程序启动时创建测试数据
我们正在用SpringBoot开发我们的应用程序,目前正在通过RESTAPI在每次运行时创建测试数据。现在我们想创建一个引导脚本,它应该在启动时运行,并创建开发/测试等过程中需要的所有对象 我来自Grails,那里有一个引导类可以实现这一点 现在我修改了我们的Application.java类来运行另一个类中的方法,该类应该创建我们的对象,但我不能在其中注入我们的服务 处理这种情况的最佳解决方案是什么 问候Java 在应用程序启动时创建测试数据,java,spring,development-environment,Java,Spring,Development Environment,我们正在用SpringBoot开发我们的应用程序,目前正在通过RESTAPI在每次运行时创建测试数据。现在我们想创建一个引导脚本,它应该在启动时运行,并创建开发/测试等过程中需要的所有对象 我来自Grails,那里有一个引导类可以实现这一点 现在我修改了我们的Application.java类来运行另一个类中的方法,该类应该创建我们的对象,但我不能在其中注入我们的服务 处理这种情况的最佳解决方案是什么 问候 Alexander在我们的应用程序类中,我们现在有以下代码: public static
Alexander在我们的应用程序类中,我们现在有以下代码:
public static void main(String[] args) {
System.out.println("spring.profiles.active="+System.getProperty("spring.profiles.active"));
ConfigurableApplicationContext ctx = SpringApplication.run(Application.class, args);
System.out.println("Application Running!!!");
autogenerateDatabaseTestdata(ctx);
}
private static void autogenerateDatabaseTestdata(ConfigurableApplicationContext ctx) {
ctx.getBean(DataGenerator.class).run(ctx);
}
数据生成器如下所示:
@Component
public class DataGenerator {
@Value("${spring.jpa.hibernate.ddl-auto}")
private String schemaDllHandling;
@Value("${db.autogenerate_data}")
private Boolean isAutogenerateData;
public void run(ConfigurableApplicationContext ctx) {
if (isAutogenerateData == null || !isAutogenerateData || !"create".equalsIgnoreCase(schemaDllHandling)) {
return; // Do nothing
}
System.out.println("Running Bootstrap:");
ctx.getBean(CountryBootstrap.class).run();
System.out.println("Bootstrap finished!");
}
}
@Component
public class CountryBootstrap {
@Autowired
CountryService countryService;
public CountryBootstrap() {
}
@Autowired
public CountryBootstrap(CountryService countryService) {
this.countryService = countryService;
}
public void run() {
countryService.saveCountry(new Country("Deutschland", "DE"));
}
}
例如,countryBootstrap如下所示:
@Component
public class DataGenerator {
@Value("${spring.jpa.hibernate.ddl-auto}")
private String schemaDllHandling;
@Value("${db.autogenerate_data}")
private Boolean isAutogenerateData;
public void run(ConfigurableApplicationContext ctx) {
if (isAutogenerateData == null || !isAutogenerateData || !"create".equalsIgnoreCase(schemaDllHandling)) {
return; // Do nothing
}
System.out.println("Running Bootstrap:");
ctx.getBean(CountryBootstrap.class).run();
System.out.println("Bootstrap finished!");
}
}
@Component
public class CountryBootstrap {
@Autowired
CountryService countryService;
public CountryBootstrap() {
}
@Autowired
public CountryBootstrap(CountryService countryService) {
this.countryService = countryService;
}
public void run() {
countryService.saveCountry(new Country("Deutschland", "DE"));
}
}
在Application.yml中,我们有一个值指示是否应导入自动生成的数据:
db:
autogenerate_data: true
这是我们在应用程序启动时插入测试数据的解决方案