有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在Spring中使用连接到当前应用程序上下文的环境初始化propertyplaceholder?

我使用的是SpringFramework 3.2.6。释放

我试图通过以下方式使用命令行界面(使用JOptCommandLinePropertySource)设置属性

PropertySource<?> propertySource = new JOptCommandLinePropertySource(options);
final GenericApplicationContext context = new GenericApplicationContext();
context.getEnvironment().getPropertySources().addFirst(propertSource);
...

我有一个bean配置器:

package com.example;

@Configuration
public class AppConfig {
  @Value("${prop1}")
  private String prop1;

  @Bean
  public MyBean myBean() {
    MyBean ret = new MyBean();
    ret.init(prop1);
    return ret;
  }
}

我用命令行参数启动程序:--prop1=prop\u值

如果我使用此xml进行初始化:

<beans>
  <context:annotation-config />
  <context:property-placeholder />
  <context:component-scan base-package="com.example" />
</beans>

然后我得到了这个错误:无法解析字符串值“${prop1}”中的占位符“prop1”

13:47:36.932 [main] DEBUG o.s.b.f.annotation.InjectionMetadata - Processing injected method of bean 'AppConfig': AutowiredFieldElement for private java.lang.String com.example.AppConfig.prop1
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'AppConfig': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private java.lang.String com.example.AppConfig.prop1; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'prop1' in string value "${prop1}"
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289) ~[spring-beans-3.2.6.RELEASE.jar:3.2.6.RELEASE]
...

但是使用这种xml,一切都很好:

<beans>
  <context:annotation-config />
  <context:component-scan base-package="com.example" />

  <bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
    <property name="environment" ref="environment" />
  </bean>
</beans>

为什么PropertySourcesPlaceholderConfigurer不检查当前应用程序上下文在Javadoc中定义的环境

Specialization of PlaceholderConfigurerSupport that resolves ${...} placeholders within bean definition property values and @Value annotations against the current Spring Environment and its set of PropertySources.


共 (1) 个答案

  1. # 1 楼答案

    使用名称空间配置时,建议使用版本较少的xsd。因此,建议使用http://www.springframework.org/schema/context/spring-context.xsd代替http://www.springframework.org/schema/context/spring-context-2.5.xsd。这确保了spring将使用类路径上可用的最新版本的xsd

    关于<context:property-placeholder />有一些,破环(?),Spring3.1中关于默认配置的更改。在Spring3.1之前,system-properties-mode属性的默认值是回退,这在Spring3.1中导致创建PropertyPlaceholderConfigurer而不是PropertySourcesPlaceholderConfigurer。默认值在特定xsd中配置。(好像Spring3.1是环境

    因此,使用较旧的xsd会导致属于该xsd特定版本的默认行为,请切换到3.2 xsd或版本较少的xsd。(如前所述,建议使用后者)