如果我有:
@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)
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方法访问属性
Asa*_*Asa 11
如果您坚持使用Spring 3.1之前的版本,则可以使用
somePropValue = ctx.getBeanFactory().resolveEmbeddedValue("${someProp}");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
44658 次 |
| 最近记录: |