Spring 配置文件解析与读取

1,配置文件的读取与解析(将property添加到环境中)

<context:property-placeholder />和@PropertySource+propertySourcesPlaceholderConfigurer的方式,都是将properties配置文件中的值存储到Spring的 Environment中。

1)xml文件的方式配置。

<!--在applicationContext.xml文件中指定,属性配置文件-->
<context:property-placeholder location="classpath:properties/finance.properties" />

<!-- 在web.xml中指定应用配置文件的位置-->
<context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            classpath:applicationContext.xml
        </param-value>
</context-param>

2)基于java-based的方式配置。

@Configuration
@PropertySource("classpath:properties/finance.properties")
public class PropertiesConfig {

   @Bean
   public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
      return new PropertySourcesPlaceholderConfigurer();
   }
}
//多配置文件
@Configuration
@PropertySources({@PropertySource(value = "classpath:properties/finance-${finance.env}.properties")})
public class PropertiesConfig {//${finance.env},会从jvm设置的-D参数中取。eg:prod,local等。

   @Bean
   public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
      return new PropertySourcesPlaceholderConfigurer();
   }
}

3)使用(在@Configuration注解的类中)

    @Value("${jdbc.url}")
    private String url;

    @Value("${jdbc.username}")
    private String username;

    @Autowired
    private Environment environment;
    String property = environment.getProperty("jdbc.password");
<bean id="dataSource"><!--beans中-->
  <property name="url" value="${jdbc.url}" />
</bean>

2,代码分析

1)PropertySourcesPlaceholderConfigurer实现了EnviromentAware接口。可以从spring拿到enviroment,然后将property设置进去

image.png

image.png

2)Environment实现了接口PropertyResolver提供方法去读取配置文件中的值
image.png

3)命名空间的处理器,在spring初始化的时候,参与解析配置文件。
image.png

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容