I want to optionally bind a field to specific class for each profile
the example code is as follows ...
spring:
config:
activate:
on-profile: test1
app:
cash:
conn:
connection-timeout: 1000
response-timeout: 2000
...
---
spring:
config:
activate:
on-profile: test2
@Getter
@Validated
@ConstructorBinding
@ConfigurationProperties(value = "app.cash.conn")
@RequiredArgsConstructor
public class CashBoxConnectionProperties {
@NotNull
@Positive
private final Integer connectionTimeout;
@NotNull
@Positive
private final Integer responseTimeout;
@NotNull
@PositiveOrZero
private final Integer retryMaxAttempts;
@NotNull
@Positive
private final Integer retryMaxDelay;
}
When running as test1
profile, the application runs normally because the properties value is set, but when running as test2
profile, the error 'Binding to target...' occurs because there is no app.cash.conn
properties.
The CashBoxConnectionProperties
is not required in test2
profile, so is there any other way than to remove @NotNull
annotation?
CodePudding user response:
You can annotate the CashBoxConnectionProperties
class with @Profile("test2")
, which makes it only available when the test2
profile is active. To make it work, the class should be marked as @Component
, since @Profile
is only applicable to Spring beans.
For more details check the documentation.
CodePudding user response:
You can use validation groups, to turn off validation for specific fields.
I never used this myself, but you can find an explanation here: https://www.baeldung.com/javax-validation-groups