直接从 Spring 上下文获取 .properties 文件中的值

use*_*610 4 spring

在标准 Spring 应用程序中,可以定义一个 PropertyPlaceholderConfigurer,它将加载一个或多个属性文件。然后,文件中定义的值将对应用程序的其余部分可见,无论是 XML ( "${}") 还是 Java (@Value ) 形式。

有没有办法,一旦加载了上下文,就可以从上下文本身获取这样的属性值,就像可以检索 bean 一样(ctx.getBean("bean-name") ) 一样?

我尝试了以下方法,但它不起作用:

GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
ctx.load("classpath:META-INF/spring/spring-context.xml");
ctx.refresh();
ctx.start();
ctx.getEnvironment().getProperty("key-name")); // RETURNS NULL
Run Code Online (Sandbox Code Playgroud)

谢谢

And*_*fan 5

您需要访问BeanFactory

ctx.getBeanFactory().resolveEmbeddedValue("${key-name}");
Run Code Online (Sandbox Code Playgroud)

  • 您可以使用环境:`env.resolvePlaceholders("${key-name:default-value}")`来注入环境,您的类可以实现`EnvironmentAware`,或者您可以从`ApplicationContext`中注入环境,因为它扩展了`EnvironmentCapable`班级。 (2认同)