Spring 配置文件解析与读取

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

和@PropertySource+propertySourcesPlaceholderConfigurer的方式,都是将properties配置文件中的值存储到Spring的 Environment中。

1)xml文件的方式配置。






        contextConfigLocation
        
            classpath:applicationContext.xml
        

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");

  

2,代码分析

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

image.png

Spring 配置文件解析与读取_第1张图片
image.png

2)Environment实现了接口PropertyResolver 提供方法去读取配置文件中的值
Spring 配置文件解析与读取_第2张图片
image.png

3)命名空间的处理器,在spring初始化的时候,参与解析配置文件。
Spring 配置文件解析与读取_第3张图片
image.png

你可能感兴趣的:(Spring 配置文件解析与读取)