简体   繁体   中英

How can I interpolate a class constant in a Spring `@Value` annotation?

I want to let Spring assign a property value.

public class Foobar {

    @Value("${example.property.foo:bar}")
    private String foo;
}

Let's say I want to refer to example.property.foo in several different places, so I'd rather assign the flag as a constant on Foobar:

public class Foobar {
    public static final String FOO_PROPERTY_FLAG = "example.property.foo";
}

The setting of example.property.foo=whatever happens elsewhere (as a system property, or in a @TestPropertySource ).

How can I refer to FOO_PROPERTY_FLAG in the annotation? This works:

@Value("${" + FOO_PROPERTY_FLAG + ":bar}")

But it's kind of ugly. Can I use the "#{}" expression syntax here somehow?

@Value("${#{FOO_PROPERTY_FLAG}:bar}")  // doesn't work; value is never injected

You can do something like:

public static final String KEY = "propertyName";

@Value("#{T(a.b.c.package.MyConstants).KEY}")

The important part is to specify package and class. Otherwise spring will try to lookup constant in BeanExpressionContext which is actually executing your SpEL

private @Value("${propertyName}") String propertyField;

No getters or setters!

With the properties being loaded via the config:

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
      p:location="classpath:propertyFile.properties" name="propertiesBean"/>

There's also the totally non-Xml version:

@PropertySource("classpath:propertyFile.properties")
public class AppConfig {

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }

Make sure and add in the namespace URI xmlns:p="springframework.org/schema/p" ; to use the p: prefixed attributes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM