In Spring-boot you can use the @Profile(!dev)
annotation to exclude beans and classes from being provided when certain profiles are active or not active. Is there an equivalent property for this that can be used inside the application.yml?
CodePudding user response:
You can use @ConditionalOnProperty.
@Bean
@ConditionalOnProperty(name = "stage", havingValue = "prod")
public NotificationSender notificationSender2() {
return new SmsNotification();
}
Which will be disabled if you have stage=dev
in your application properties.
There's blog from Eugen on it: https://www.baeldung.com/spring-conditionalonproperty
CodePudding user response:
Why not use profile seperators in configuration file?
---
spring:
profiles: dev
my-app.some-property: ...
---
spring:
profiles: uat
my-app.some-property: ...
Or like GeertPt said in, you can use org.springframework.boot.autoconfigure.condition.ConditionalOnProperty
annotation to deal with your bean creation.
Even if you want you profile to be dev
, you can use a feature flag to enable a bean. This might be helpful where you have to maintain multiple profiles.
For instance, I needed to log few properties on my stag server, but I was not willing to change in code base. So, with below, I only need to change the config-repo file and set the flag accordingly.
my-app-dev.yml
my-app:
cloud:
config:
log-details: true
log-ssl-properties: true
swagger:
enabled: false
ConditionalConfigurationPropertiesLogger.java
@Slf4j
@Component
@Profile({"native", "dev"})
@ConditionalOnProperty(name = "my-app.cloud.config.log-details", havingValue = "true")
public class ConditionalConfigurationPropertiesLogger implements CommandLineRunner {
@Override
public void run(String... args) {
log.info(" <details> ");
}
}
}