Home > Net >  Run CommandLineRunner Bean when ddl-auto is set to create in Spring
Run CommandLineRunner Bean when ddl-auto is set to create in Spring

Time:11-04

I have this CommandLineRunner in my Main class (ReservationprojectApplication)

@Bean
    CommandLineRunner run(UserService userService) {
        return args -> {
            userService.saveRole(new Role(null, "ROLE_ADMIN"));
            userService.saveRole(new Role(null, "ROLE_STUDENT"));

            userService.saveUser(new User("administrator", "[email protected]", "t", new ArrayList<>(), Instant.now(), true));
            userService.saveUser(new User("elias", "[email protected]", "t", new ArrayList<>(), Instant.now(), true));

            userService.addRoleToUser("administrator", "ROLE_ADMIN");
            userService.addRoleToUser("elias", "ROLE_STUDENT");
        };
    }

Is there a way to only run this code once the ddl-auto is set to create? I don't want to comment this code each time my ddl-auto is set to update.

spring:
  # Database properties
  datasource:
    password: blabla
    url: jdbc:postgresql://localhost:5432/cegeka_reservation
    username: postgres
  jpa:
    hibernate:
      **ddl-auto: update**
    properties:
      hibernate:
        dialect: org.hibernate.dialect.PostgreSQLDialect
        format_sql: true
        show_sql: true

Thanks in advance!

CodePudding user response:

The simplest solution would be using the @ConditionalOnProperty annotation as shown below, which checks if the specified properties have a specific value, for more details about conditional beans with Spring Boot check the blog post.

@Bean
@ConditionalOnProperty(
    name = {"spring.jpa.hibernate.dll-auto"},
    havingValue = "create")
CommandLineRunner run(UserService userService) {
    //...
}

CodePudding user response:

You should have access to the property so it is easy enough to check it

@Value("${spring.jpa.hibernate.ddl-auto}")
private String ddl;

@Bean
CommandLineRunner run(UserService userService) {
  if ("create".equals(ddl) {
    // Rest of your code here
  }
}
  • Related