1敢靡,配置文件的讀取與解析(將property添加到環(huán)境中
)
<context:property-placeholder />和@PropertySource+propertySourcesPlaceholderConfigurer的方式漫拭,都是將properties配置文件中的值存儲到Spring的 Environment中碳锈。
1)xml文件的方式配置。
<!--在applicationContext.xml文件中指定召夹,屬性配置文件-->
<context:property-placeholder location="classpath:properties/finance.properties" />
<!-- 在web.xml中指定應(yīng)用配置文件的位置-->
<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設(shè)置的-D參數(shù)中取恕沫。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實現(xiàn)了EnviromentAware接口婶溯。可以從spring拿到enviroment鲸阔,然后將property設(shè)置進(jìn)去
image.png
image.png
2)Environment實現(xiàn)了接口PropertyResolver
提供方法去讀取配置文件中的值
image.png
3)命名空間的處理器,在spring初始化的時候迄委,參與解析配置文件褐筛。
image.png