Search code examples
javaspringhibernatespring-bootentity

(Workaround for) Use of @ConditionalOnProperty on Entity


We have a Spring-Boot application with some database-entity-classes.

We use ddl-auto: validate to make sure the connected database has correct schema.

Now we are at the point where we add a feature which is toggle-able to match different environments, the NewFeatureService is annotated with @ConditionalOnProperty("newfeature.enabled").

Everything works fine until here.

The problem is that the feature requires a database entity.

@Entity
@ConditionalOnProperty("newfeature.enabled")  // <--- doesn't work
public class NewFeatureEnitity{...}

@ConditionalOnProperty will obviously not work but what is a good way to tell Hibernate only to validate this Entity against the database if a property is set.

What we don't want:

  • add this table in all databases even if feature isn't used
  • having different artifacts

Solution

  • Just to be sure that it's not overseen i want to provide my suggestion as an answer.

    It makes a bit more use of spring-boot than the answer provided by O.Badr.

    You could configure your spring-boot application to only scan your core entities like this:

    @SpringBootApplication
    @EntityScan("my.application.core")
    public class Application {
    
      public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
      }
    }
    

    So you are able to provide your optional entities (and features) in a package like my.application.features (feel free to use any other structure but a package outside the previously specified base package).

    @ConditionalOnProperty("newfeature.enabled")
    @Configuration
    @EntityScan("my.application.features.thefeature")
    public class MyFeatureConfiguration {
      /*
      * No Configuration needed for scanning of entities. 
      * Do here whatever else should be configured for this feature.
      */
    }