【问题标题】:Define '*.properties' file location in Spring在 Spring 中定义 '*.properties' 文件位置
【发布时间】:2015-11-10 17:13:55
【问题描述】:

我有几个 bean 的 Spring 上下文,例如:

<bean id="anyBean" class="com.my.app.AnyBean"
   p:test_user="${any1}"
   p:test_pass="${any2}">
</bean>

要解析这些占位符(${any1} 和 ${any2}),我使用:

<bean id="propertyPlaceholderConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" p:location="my.properties" />

它工作正常,但我需要从主类的 'main' 方法中定义 'my.properties' 的位置。像这样:

ApplicationContext context = new ClassPathXmlApplicationContext(my_xml_config.xml);
PropertyPlaceholderConfigurer ppc = context.getBean("propertyPlaceholderConfigurer", PropertyPlaceholderConfigurer.class);

Resource resource = context.getResource("path/to/my.properties");
ppc.setLocation(resource);

但是当我尝试启动它时:

线程“main”中的异常 org.springframework.beans.factory.BeanDefinitionStoreException: 类路径中定义的名称为“AnyBean”的无效 bean 定义 资源 [my_xml_config.xml]:无法解析占位符“any1” 字符串值“${any1}”

您能否提示有什么方法可以解决这个问题?

【问题讨论】:

    标签: java spring properties


    【解决方案1】:

    当你尝试得到一个 bean 时

    PropertyPlaceholderConfigurer ppc = context.getBean("propertyPlaceholderConfigurer", PropertyPlaceholderConfigurer.class);
    

    Spring 已尝试刷新您的上下文,但由于该属性不存在而失败。您需要通过 specifying it in the constructor 阻止 Spring 执行此操作

    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"my_xml_config.xml"}, false);
    

    由于ApplicationContext 没有刷新,PropertyPlaceholderConfigurer bean 不存在。

    为此,您需要使用 PropertySourcesPlaceholderConfigurer 而不是 PropertyPlaceholderConfigurer(感谢 M.Deinum)。您可以使用与 PropertyPlaceholderConfigurer bean 相同的方式在 XML 中声明它,或者使用

    <context:property-placeholder />
    

    您需要利用PropertySourcesPlaceholderConfigurer 有自己的位置这一事实,而且还使用在ApplicationContextEnvironment 中注册的PropertySource 实例。

    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"your_config.xml"}, false);
    // all sorts of constructors, many options for finding the resource
    ResourcePropertySource properties = new ResourcePropertySource("path/to/my.properties");
    context.getEnvironment().getPropertySources().addLast(properties);
    context.refresh();
    

    【讨论】:

    • PropertyPlaceholderConfigurer 不咨询 PropertySources,PropertySourcesPlaceholderConfigurer 咨询。而不是配置 bean 使用&lt;context:property-placeholder /&gt; 标签,默认(在最近的春季版本中)为PropertySourcesPlaceholderConfigurer
    • @M.Deinum OP 想要以编程方式设置属性位置。我猜&lt;context:property-placeholder /&gt; 不是一个选项。
    • 为什么不呢,你仍然可以使用它的 location 属性。将文件名设置为系统属性,spring 将使用它。
    • PropertyPlaceHolderCongigurer 是否应该留在 XML spring cofig 中?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-21
    • 1970-01-01
    • 2014-06-29
    • 2021-10-21
    • 2015-03-13
    • 2015-10-16
    • 2018-06-12
    相关资源
    最近更新 更多