Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make spring @Value take default value from static field

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?

like image 555
Ruslan Akhundov Avatar asked Oct 28 '25 07:10

Ruslan Akhundov


1 Answers

I would do @Value("${foo.bar.my-property:" + DEFAULT_PROPERTY_VALUE + "}")

like image 131
Vyncent Avatar answered Oct 31 '25 01:10

Vyncent