pixel
pixel

Reputation: 10587

How to use feature flags to disable application.properties setting

I understand that I can use @ConditionalOnExpression to enable or disable a component such as a @RestController, or @Service, or @Entity. That is all clear.

However, Spring Boot has more. It has application.properties configuration, it has @Autowired properties, it has @Test classes/methods.

For example, given I have feature flag defined in my application.properties file as:

myFeature.enabled=false

I want to disabled following:

    // I want to disable all these using myFeature.enabled flag
    spring.jpa.hibernate.ddl-auto=update
    spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/db_example
    spring.datasource.username=springuser
    spring.datasource.password=ThePassword
    spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
    #spring.jpa.show-sql: true
    @Component
    public class FooService {  
        @Autowired
        private Foo foo; // I want to disable only this property using myFeature.enabled flag
    }
    @SpringBootTest
    public class EmployeeRestControllerIntegrationTest {
    
        ...
    
        // tests methods
    }

How do I disable these using myFeature.enabled flag?

I know that in case of an @Entity or @Controller class I can simply do something like below, but I dont know how to use same mechanism to disable the 3 above cases:

@Entity
@ConditionalOnExpression(${myFeature.enabled})
public class Employee {
   ...
}

Upvotes: 0

Views: 1044

Answers (1)

Hopey One
Hopey One

Reputation: 1816

From your question, I think using spring profiles is a much better fit. With profiles you can:

  • have an application-{profile}.properties file containing profile-specific properties that are only used if the profile is active.
  • You can choose to enable a specific implementation of your FooService and disable the default version if a profile is active.
  • You can enable a test only if the profile is active.

Upvotes: 1

Related Questions