I have a java configuration where I create bean using some properties, defined in application.properties
. For one of them I have a default value which is pretty long, so I extracted this value to a public static final String
field of this configuration, now I want to make @Value
use it as a default value.
So eventually I want something like this:
@Configuration
public class MyConfiguration {
public static final String DEFAULT_PROPERTY_VALUE = "long string...";
@Bean("midPriceDDSEndpoint")
public DistributedDataSpace<Long, MidPriceStrategy> midPriceDDSEndpoint(
@Value("${foo.bar.my-property:DEFAULT_PROPERTY_VALUE}") String myPropertyValue) {
... create and return bean...
}
}
However by spring doesn't my field, so I am curious if I can somehow make it lookup it.
One way to fix this, is to access this static field through the configuration bean: @Value(${foo.bar.my-property:#{myConfigurationBeanName.DEFAULT_PROPERTY_VALUE}})
, but using this approach makes constructor unreadable, because Value
annotation then takes a lot of space(as property name and configuration bean name is longer then in this example). Is there any other way to make spring use static field as a default value for property?
You may just want to inject Environment
, and get the value as default like so:
@Configuration
public class MyConfiguration {
public static final String DEFAULT_PROPERTY_VALUE = "long string...";
@Autowired
private Environment env;
@Bean("midPriceDDSEndpoint")
public DistributedDataSpace<Long, MidPriceStrategy> midPriceDDSEndpoint() {
String myPropertyValue = env.getProperty("foo.bar.my-property", DEFAULT_PROPERTY_VALUE);
}
}
I personally think that's a little bit more readable...