0

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:

  • database connectivity settings in application.properties
    // 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
  • an@Autowired property in a class and I only want to disable that one injected property
    @Component
    public class FooService {  
        @Autowired
        private Foo foo; // I want to disable only this property using myFeature.enabled flag
    }
  • Test class and I want to disable it (I know I can use @Ignore or @Disable) 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 {
   ...
}
Ken White
  • 123,280
  • 14
  • 225
  • 444
pixel
  • 9,653
  • 16
  • 82
  • 149

1 Answers1

1

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.
Hopey One
  • 1,681
  • 5
  • 10
  • Thanks, I am aware of profiles, I use them already but that is not what I am looking for. I am asking about feature flags – pixel Feb 27 '23 at 15:53