如何从ApplicationContext对象获取属性值?(不使用注释)

Hap*_*eer 43 spring spring-el

如果我有:

@Autowired private ApplicationContext ctx;
Run Code Online (Sandbox Code Playgroud)

我可以使用其中一个getBean方法获取bean和资源.但是,我无法弄清楚如何获得属性值.

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

private @Value("${someProp}") String somePropValue;
Run Code Online (Sandbox Code Playgroud)

我在ApplicationContext对象上调用什么方法来获取该值而不自动装配bean?

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

Ita*_*tto 52

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

somePropValue = ctx.getEnvironment().getProperty("someProp");
Run Code Online (Sandbox Code Playgroud)

  • 在运行时使用Environment(仅适用于启动)通常是一个非常糟糕的主意,因为它通过JNDI和寻找值的其他位置,这是昂贵的. (3认同)

Sea*_*oyd 15

假设该${someProp}属性来自PropertyPlaceHolderConfigurer,这会让事情变得困难.PropertyPlaceholderConfigurer是一个BeanFactoryPostProcessor,因此仅在容器启动时可用.因此,bean在运行时无法使用这些属性.

解决方案是创建某种值持有者bean,使用您需要的属性/属性进行初始化.

@Component
public class PropertyHolder{

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

    // + getter methods
}
Run Code Online (Sandbox Code Playgroud)

现在将PropertyHolder注入需要属性的位置,并通过getter方法访问属性

  • @Webnet我明白了,但AFAIK在Spring中是不可能的(至少没有PropertyPlaceholderConfigurer机制) (2认同)

Asa*_*Asa 11

如果您坚持使用Spring 3.1之前的版本,则可以使用

somePropValue = ctx.getBeanFactory().resolveEmbeddedValue("${someProp}");
Run Code Online (Sandbox Code Playgroud)