从API上我们已经看出解析器的作用了,具体功能就不要罗嗦了。示例如下:
@Test
public void test() throws Exception {
//省略propertySources
PropertyResolver propertyResolver = new PropertySourcesPropertyResolver(propertySources);
System.out.println(propertyResolver.getProperty("encoding"));
System.out.println(propertyResolver.getProperty("no", "default"));
System.out.println(propertyResolver.resolvePlaceholders("must be encoding ${encoding}")); //输出must be encoding gbk
}
从如上示例可以看出其非常简单。另外Environment也继承了PropertyResolver。
Environment
环境,比如JDK环境,Servlet环境,Spring环境等等;每个环境都有自己的配置数据,如System.getProperties()、System.getenv()等可以拿到JDK环境数据;ServletContext.getInitParameter()可以拿到Servlet环境配置数据等等;也就是说Spring抽象了一个Environment来表示环境配置。
public interface Environment extends PropertyResolver {//继承PropertyResolver
//得到当前明确激活的剖面
String[] getActiveProfiles();
//得到默认激活的剖面,而不是明确设置激活的
String[] getDefaultProfiles();
//是否接受某些剖面
boolean acceptsProfiles(String... profiles);
}
从API上可以看出,除了可以解析相应的属性信息外,还提供了剖面相关的API,目的是: 可以根据剖面有选择的进行注册组件/配置。比如对于不同的环境注册不同的组件/配置(正式机、测试机、开发机等的数据源配置)。它的主要几个实现如下所示:
MockEnvironment:模拟的环境,用于测试时使用;
StandardEnvironment:标准环境,普通Java应用时使用,会自动注册System.getProperties() 和 System.getenv()到环境;
StandardServletEnvironment:标准Servlet环境,其继承了StandardEnvironment,Web应用时使用,除了StandardEnvironment外,会自动注册ServletConfig(DispatcherServlet)、ServletContext及JNDI实例到环境;
除了这些,我们也可以根据需求定义自己的Environment。示例如下:
@Test
public void test() {
//会自动注册 System.getProperties() 和 System.getenv()
Environment environment = new StandardEnvironment();
System.out.println(environment.getProperty("file.encoding"));
}
其默认有两个属性:systemProperties(System.getProperties())和systemEnvironment(System.getenv())。
在web环境中首先在web.xml中配置:
myConfig hello spring org.springframework.web.servlet.DispatcherServlet contextConfigLocation classpath:spring-mvc.xml
使用StandardServletEnvironment加载时,默认除了StandardEnvironment的两个属性外,还有另外三个属性:servletContextInitParams(ServletContext)、servletConfigInitParams(ServletConfig)、jndiProperties(JNDI)。
然后在程序中通过如下代码注入Environment:
@Autowired
Environment env;
另外也可以直接使用ApplicationContext.getEnvironment()获取;接着就可以用如下代码获取配置:
System.out.println(env.getProperty("myConfig"));
System.out.println(env.getProperty("contextConfigLocation"));
另外我们在运行应用时可以通过-D传入系统参数(System.getProperty()),如java -Ddata=123 com.sishuok.spring3.EnvironmentTest,那么我们可以通过environment.getProperty("data") 获取到。
如果我们拿到的上下文是ConfigurableApplicationContext类型,那么可以:ctx.getEnvironment().getPropertySources() ;然后通过PropertySources再添加自定义的PropertySo