How to get raw value of property containing placeholders?

血红的双手。 提交于 2019-12-07 07:15:13

问题


I am trying to define the following property in one of my .properties files:

personExpression=${person.surname}

This is then read by a config class:

@Configuration
public class TemplateConfig {
    @Autowired
    private Environment environment;

    public String getPersonExpression() {
        return environment.getProperty("personExpression");
    }
}

However this gives the exception:

java.lang.IllegalArgumentException: Could not resolve placeholder 'person.surname' in string value "${person.surname}"

Is there a way to do get getPersonExpression() to return the string literal ${person.surname} without attempting to resolve it?


回答1:


To get this to work takes some pretty unintuitive syntax.

You essentially have to split your expression into two parts and wrap the whole thing in a parent SpEL expression to join them.

If you change your property value to the following it should work:

personExpression=#{'$' + '{person.surname}'}

This works because you're splitting up the $ character from the {person.surname} so SpEL won't try to evaluate it as an expression, because as far as it's concerned, you're just concatenating two strings together.




回答2:


I don't know of any getRawPropertyValue type method that's accessible through the ApplicationContext.

If you know the name of your PropertySource, eg. example, you can get the ConfigurableEnvironment, and its registered PropertySources, retrieve the appropriate one, and get the required property value.

AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(Sample.class);
ConfigurableEnvironment configurableEnvironment = ctx.getEnvironment();
String rawValue = configurableEnvironment.getPropertySources()
                       .get("example") // get property source
                       .getProperty("personExpression"); // get property

The variable rawValue will have the value ${person.surname}. All this is done outside any property placeholder resolvers.

This will obviously only work for property sources registered with the Environment.




回答3:


you might know this, but i'm just clarifying ${} is used to retrieve a property from properties file in to an XML file/ any other file where valid.

If you are trying to set personExpression= "person.surname" and want to retrieve it as you are doing it above (environment.getProperty("personExpression");) you should define like this personExpression= person.surname in your properties file. then it will work with environment.getProperty("personExpression"); and returns person.surname in your function, hope this helps



来源:https://stackoverflow.com/questions/34584498/how-to-get-raw-value-of-property-containing-placeholders

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