How do I create dummy data when the application starts only in dev profile?
I'm following this article to work with profiles in spring boot. I need to create dummy data when the application starts, but only in the dev profile. How do I achieve this?
My class implements ApplicationRunner and overrides the run method to create the data. I've tried to use the @Profile("dev") annotation as in the article but the data is created irrespective of the active profile.
@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);
}
}
In application.properties, I have
spring.profiles.active=test
A dummy user should be created only when the active profile is dev but it is being created in test profile as well.
@Profile should be marked with @Bean or @Component or its stereotype (i.e @Serivce , @Controller , @Repository etc.)
Simply change it to :
@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);
}
}
The code of DEV ApplicationRunner will only run if DEV profile is enabled such as through application.properties:
spring.profiles.active=dev
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With