【问题标题】:Spring Java Configuration and property placeholder resolutionSpring Java 配置和属性占位符解析
【发布时间】:2014-03-23 09:32:09
【问题描述】:

我正在尝试在未明确声明 PropertySourcesPlaceholderConfigurer bean 时,Spring 如何解析属性占位符。查看通过注解通过 java 配置 spring 的现有项目的源代码。 . .

在spring上下文xml中:

<context:component-scan base-package="com.myproject.config" />

在一个引导其余应用程序和配置的 java 文件中

package com.myproject.config;

@Configuration
@ComponentScan(basePackages = {"com.myproject.app"})
@PropertySource("config/${app.env}.properties")
public class RootConfig {

}

这一切都非常巧妙,但我一生都无法弄清楚是什么告诉 Spring 根据环境变量评估 ${...} 属性占位符语法。我一直无法在 spring 文档中找到答案,尽管我知道 spring 依赖于 PropertySourcesPlaceholderConfigurer 类来做到这一点。关于何时/如何隐式调用这个类,没有任何线索可以告诉我。是通过@Configuration注解,还是在spring bootstrapping过程的另一部分?

我知道这不是最恰当的理解,但我不喜欢将任何东西写成“Spring Magic”。对此的任何见解都会令人惊叹!

【问题讨论】:

    标签: spring spring-3 spring-java-config spring-profiles


    【解决方案1】:
        @Configuration
    @PropertySource("classpath:property.property")
    public class ConfigClass {
    
        @Autowired Environment env;
    
        @Bean
        public Entity getEntity(){
            Entity entity = new Entity();
            entity.setUsername(env.getProperty("jdbc.username"));
            entity.setDriverClassName(env.getProperty("jdbc.driverClassName"));
            entity.setPassword(env.getProperty("jdbc.password"));
            entity.setUrl(env.getProperty("jdbc.url"));
            return entity;
        }
    
    }
    

    【讨论】:

      【解决方案2】:

      每个 Spring @Configuration documentation,您的 RootConfig 类必须从某个地方“引导”,下面是一些示例。

      通过AnnotationConfigApplicationContext

      AnnotationConfigApplicationContext context = 
             new AnnotationConfigApplicationContext();
      ccontext.register(RootConfig.class);
      

      通过 Spring xml

      <beans>
        <context:annotation-config/>
        <bean class="...RootConfig"/>
      </beans>
      

      您是否检查过引导RootConfig 的源以查看是否已声明PropertySourcesPlaceholderConfigurer?例如:

      <context:property-placeholder/>
      

      【讨论】:

        【解决方案3】:

        我会尝试这样做:

        @PropertySource("config/#{ systemProperties['app.env'] }.properties")

        (来源:http://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/expressions.html#expressions-beandef-xml-based) 让我知道它是否被评估。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2015-05-22
          • 2017-09-15
          • 2012-12-20
          • 2015-01-16
          • 2021-03-08
          • 2011-12-10
          • 2017-01-12
          相关资源
          最近更新 更多