【问题标题】:How do I get a property value from an ApplicationContext object? (not using an annotation)如何从 ApplicationContext 对象中获取属性值? (不使用注释)
【发布时间】:2012-06-05 01:57:38
【问题描述】:

如果我有:

@Autowired private ApplicationContext ctx;

我可以使用其中一种 getBean 方法来获取 bean 和资源。但是,我不知道如何获取属性值。

显然,我可以创建一个具有 @Value 属性的新 bean,例如:

private @Value("${someProp}") String somePropValue;

在不自动装配 bean 的情况下,我应该在 ApplicationContext 对象上调用什么方法来获取该值?

我通常使用@Value,但是有一种情况需要SPeL表达式是动态的,所以不能只使用注解。

【问题讨论】:

  • (YourBeanType)ctx.getBean("beanId");

标签: spring spring-el


【解决方案1】:

假设${someProp} 属性来自PropertyPlaceHolderConfigurer,这使事情变得困难。 PropertyPlaceholderConfigurer 是一个 BeanFactoryPostProcessor,因此仅在容器启动时可用。所以这些属性在运行时对 bean 不可用。

一种解决方案是创建某种值持有者 bean,您可以使用所需的一个/多个属性对其进行初始化。

@Component
public class PropertyHolder{

    @Value("${props.foo}") private String foo;
    @Value("${props.bar}") private String bar;

    // + getter methods
}

现在在需要属性的地方注入这个 PropertyHolder 并通过 getter 方法访问属性

【讨论】:

  • 这里有一个非常有用的例子。
  • @Webnet ok,加了一个小例子
  • 这不要求PropertyHolder 是托管bean吗?我认为@HappyEngineer 正在寻找一个不是托管 bean 的解决方案(就像我一样)。
  • @Webnet 我理解,但 AFAIK 在 Spring 中是不可能的(至少不能使用 PropertyPlaceholderConfigurer 机制)
  • resolveEmbeddedValue() 答案适用于 Spring 4.3.3。只需要一个上下文,而不是一个 bean 值占位符。
【解决方案2】:

SPeL表达式需要动态的情况下,手动获取属性值:

somePropValue = ctx.getEnvironment().getProperty("someProp");

【讨论】:

  • 在运行时使用环境(仅与启动相对)通常是一个非常糟糕的主意,因为它通过 JNDI 和其他位置寻找价值,这是昂贵的。
【解决方案3】:

如果你卡在 Spring pre 3.1,你可以使用

somePropValue = ctx.getBeanFactory().resolveEmbeddedValue("${someProp}");

【讨论】:

  • 这是适用于 Spring 4.3.3 的答案。只需要一个上下文,而不是一个 bean 值占位符。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-29
相关资源
最近更新 更多