英文:
How does Spring interpolate ${x} inside a string?
问题
我有一个在Spring项目中的Java类,看起来像这样:
@Component
public class X {
private static final ApplicationContext CTX = new FileSystemXmlApplicationContext("file:${PATH}/ApplicationContext.xml");
...
}
我正在寻找关于如何在字符串参数中插值${PATH}
的参考文档。PATH
作为系统属性传递(例如 java -DPATH=...
),所以我认为它是从那里获取的,但我找不到描述这个机制的解释。它是否是与Spring相关的功能,类似于@Value
中使用的语法?
英文:
I have a java class in a Spring project that looks (edited) like:
@Component
public class X
{
private static final ApplicationContext CTX = new FileSystemXmlApplicationContext("file:${PATH}/ApplicationContext.xml");
...
I am looking for the reference explaining how the ${PATH} is interpolated in the string parameter. The PATH is passed as a system property ( java -DPATH=...) so I assume it takes it from there but I can't find an explanation describing the mechanism. Is it a Spring related feature similar to the syntax used in @Value?
答案1
得分: 2
configLocations
(类型为String
)传递给FileSystemXmlApplicationContext
构造函数之一,将由从AbstractRefreshableConfigApplicationContext
类继承的resolvePath()
方法进行处理。
resolvePath()
文档说明:
> 解析给定的路径,如果需要,用相应的环境属性值替换占位符。应用于配置位置。
>
> 另请参阅:
> PropertyResolver.resolveRequiredPlaceholders(String)
resolveRequiredPlaceholders()
文档说明:
> 解析给定文本中的${...}
占位符,将其替换为由getProperty(java.lang.String)
解析的相应属性值。无默认值的无法解析的占位符将被忽略并保持不变。
声明getProperty()
方法的PropertyResolver
实际上是一个StandardEnvironment
。
StandardEnvironment
文档说明:
> Environment
实现,适用于“标准”(即非Web)应用程序。
>
> 除了ConfigurableEnvironment
的常规功能,如属性解析和与配置文件相关的操作外,此实现还配置了两个默认的属性源,按以下顺序进行搜索:
>
> - 系统属性
> - 系统环境变量
英文:
configLocations
(type String
) passed to one of the FileSystemXmlApplicationContext
constructors are processed by the resolvePath()
method inherited from the AbstractRefreshableConfigApplicationContext
class.
resolvePath()
documentation says:
> Resolve the given path, replacing placeholders with corresponding environment property values if necessary. Applied to config locations.
>
> See Also:
> PropertyResolver.resolveRequiredPlaceholders(String)
resolveRequiredPlaceholders()
documentation says:
> Resolve ${...}
placeholders in the given text, replacing them with corresponding property values as resolved by getProperty(java.lang.String)
. Unresolvable placeholders with no default value are ignored and passed through unchanged.
The PropertyResolver
declaring that getProperty()
method is actually a StandardEnvironment
.
StandardEnvironment
documentation says:
> Environment
implementation suitable for use in 'standard' (i.e. non-web) applications.
>
> In addition to the usual functions of a ConfigurableEnvironment
such as property resolution and profile-related operations, this implementation configures two default property sources, to be searched in the following order:
>
> - system properties
> - system environment variables
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论