当应用程序仅在开发配置文件中启动时,如何创建虚拟数据?
我正在关注 this article在 spring boot 中使用配置文件。我需要在应用程序启动时创建虚拟数据,但只在开发配置文件中。我如何实现这一目标?
我的类实现了 ApplicationRunner
并覆盖了 run
方法来创建数据。我已尝试使用文章中的 @Profile("dev")
注释,但无论 Activity 配置文件如何,都会创建数据。
@SpringBootApplication
public class DemoApplication implements ApplicationRunner {
@Autowired
private UserService userService; //handles user saving
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Profile("dev")
@Override
public void run(ApplicationArguments arg0) throws Exception {
User user = new User();
user.setName("Dummy User");
userService.save(user);
}
}
在application.properties
中,我有
spring.profiles.active=test
仅当 Activity 配置文件为 dev
时才应创建虚拟用户,但它也在 test
配置文件中创建。
最佳答案
@Profile
应标记为 @Bean
或 @Component
或其原型(prototype)(即 @Serivce
, @Controller
, @Repository
等)
只需将其更改为:
@SpringBootApplication
public class DemoApplication {
@Autowired
private UserService userService; //handles user saving
@Profile("dev")
@Bean
public ApplicationRunner devApplicationRunner(){
return arg->{
User user = new User();
user.setName("Dummy User");
userService.save(user);
};
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
DEV ApplicationRunner 的代码只有在 DEV 配置文件启用时才会运行,例如通过 application.properties:
spring.profiles.active=dev
关于java - Execute ApplciationRunner run only in dev profile,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53943733/