Make spring @Value take default value from static field

回眸只為那壹抹淺笑 提交于 2020-03-15 07:35:07

问题


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?


回答1:


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...




回答2:


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




回答3:


@Vyncent's answer is limited in scope because it only works with publicly accessible static constants, since annotation attributes must be compile-time constants. To invoke a static method, use the following:

@Value("${demo.parallelism:#{T(java.lang.Runtime).getRuntime().availableProcessors()}}")
private int parallelism;

This sets parallelism = demo.parallelism JVM variable or gets the number of processors dynamically.




回答4:


I'm not 100% sure, but I think it's not possible. The real question here is why you would need to do something like that? What is the use case? You can always make a simple workaround like

private String getMyPropertyValue() {
    return myPropertyValue.equals("some_explicitly_defined_default_value") ? DEFAULT_PROPERTY_VALUE : myPropertyValue;
}


来源:https://stackoverflow.com/questions/50395101/make-spring-value-take-default-value-from-static-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!