spring boot实战(第五篇)配置源码解析

来源:互联网 发布:淘宝上论文发表靠谱吗 编辑:程序博客网 时间:2024/05/20 02:53

前言

前面的文章都采用markdown编写的,但编辑图片上极其不方便,以后还是采用网页的形式。
上一篇中讲述了spring boot配置文件的使用,本篇开始从源码的角度来看看配置文件。

环境(Environment)

学习过spring的同学都清楚,在bean中注入Enviroment实例即可调用配置资源信息,如以下代码
[java] view plain copy
  1. package com.lkl.springboot.config;  
  2.   
  3. import org.springframework.beans.factory.annotation.Autowired;  
  4. import org.springframework.core.env.Environment;  
  5. import org.springframework.stereotype.Component;  
  6.   
  7. /** 
  8.  * 注入enviroment 
  9.  *  
  10.  * @author liaokailin 
  11.  * @version $Id: DIEnviroment.java, v 0.1 2015年10月2日 下午9:17:19 liaokailin Exp $ 
  12.  */  
  13. @Component  
  14. public class DIEnviroment {  
  15.     @Autowired  
  16.     Environment environment;  
  17.   
  18.     public String getProValueFromEnviroment(String key) {  
  19.         return environment.getProperty(key);  
  20.     }  
  21. }  

      spring boot是如何来构建环境??

来看 SpringApplication.run(String... args)中的代码
[html] view plain copy
  1. // Create and configure the environment  
  2.             ConfigurableEnvironment environment = getOrCreateEnvironment();  
[html] view plain copy
  1. <p class="p1"><span class="s1">private</span> ConfigurableEnvironment getOrCreateEnvironment() {</p><p class="p1"><span>    </span><span>   </span><span class="s1">if</span> (<span class="s1">this</span>.<span class="s2">environment</span> != <span class="s1">null</span>) {</p><p class="p2"><span class="s3"><span>   </span><span>   </span><span>   </span></span><span class="s1">return</span><span class="s3"> </span><span class="s1">this</span><span class="s3">.</span>environment<span class="s3">;</span></p><p class="p1"><span>    </span><span>   </span>}</p><p class="p2"><span class="s3"><span> </span><span>   </span></span><span class="s1">if</span><span class="s3"> (</span><span class="s1">this</span><span class="s3">.</span>webEnvironment<span class="s3">) {</span></p><p class="p1"><span>  </span><span>   </span><span>   </span><span class="s1">return</span> <span class="s1">new</span> StandardServletEnvironment();</p><p class="p1"><span> </span><span>   </span>}</p><p class="p1"><span>    </span><span>   </span><span class="s1">return</span> <span class="s1">new</span> StandardEnvironment();</p><p class="p3">  
  2. </p><p class="p1"><span>  </span>}</p>  
初始environment 为空,this.webEnvironment 判断构建的是否为web环境,通过deduceWebEnvironment方法推演出为true
[html] view plain copy
  1. private boolean deduceWebEnvironment() {  
  2.         for (String className : WEB_ENVIRONMENT_CLASSES) {  
  3.             if (!ClassUtils.isPresent(className, null)) {  
  4.                 return false;  
  5.             }  
  6.         }  
  7.         return true;  
  8.     }  
由于可以得到得出构建的enviroment为StandardServletEnvironment
其类继承关系如下
 

创建对象调用其父类已经自身构造方法,StandardServletEnvironment、StandardEnvironment无构造方法,调用AbstractEnvironment构造方法

[html] view plain copy
  1. public AbstractEnvironment() {  
  2.         customizePropertySources(this.propertySources);  
  3.         if (this.logger.isDebugEnabled()) {  
  4.             this.logger.debug(format(  
  5.                     "Initialized %s with PropertySources %s", getClass().getSimpleName(), this.propertySources));  
  6.         }  
  7.     }  
首先看this.propertySources定义

[html] view plain copy
  1. private final MutablePropertySources propertySources = new MutablePropertySources(this.logger);  

从字面的意义可以看出MutablePropertySources为多PropertySource的集合,其定义如下:

[html] view plain copy
  1. public class MutablePropertySources implements PropertySources {  
  2.   
  3.     private final Log logger;  
  4.   
  5.     private final List<PropertySource<?>> propertySourceList = new CopyOnWriteArrayList<PropertySource<?>>();  ...}  
其中PropertySource保存配置资源信息
[html] view plain copy
  1. public abstract class PropertySource<T> {  
  2.   
  3.     protected final Log logger = LogFactory.getLog(getClass());  
  4.   
  5.     protected final String name;  
  6.   
  7.     protected final T source; ...}  

资源信息元数据PropertySource包含name和泛型,一份资源信息存在唯一的name以及对应泛型数据,在这里设计为泛型表明可拓展自定义类型。如需自定义或增加资源信息,即只需构建PropertySource或其子类,然后添加到

MutablePropertySources中属性List<PropertySource<?>>集合中,MutablePropertySources又作为AbstractEnvironment中的属性,因此将AbstractEnvironment保存在spring bean容器中即可访问到所有的PropertySource。

来看下对应的类图关系:

带着如上的猜想来继续查看源码。

继续来看AbstractEnvironment对应构造方法中的customizePropertySources

[html] view plain copy
  1. protected void customizePropertySources(MutablePropertySources propertySources) {  
  2.     }  

为protected且无实现的方法,将具体的实现放在子类来实现,调用StandardServletEnvironment中的具体实现:

[html] view plain copy
  1. protected void customizePropertySources(MutablePropertySources propertySources) {  
  2.         propertySources.addLast(new StubPropertySource(SERVLET_CONFIG_PROPERTY_SOURCE_NAME));  
  3.         propertySources.addLast(new StubPropertySource(SERVLET_CONTEXT_PROPERTY_SOURCE_NAME));  
  4.         if (JndiLocatorDelegate.isDefaultJndiEnvironmentAvailable()) {  
  5.             propertySources.addLast(new JndiPropertySource(JNDI_PROPERTY_SOURCE_NAME));  
  6.         }  
  7.         super.customizePropertySources(propertySources);  
  8.     }  

这里调用的propertiesSources即为AbstractEnvironment中的属性,该方法将往集合中添加指定名称的PropertySource;来看下addLast方法:

[html] view plain copy
  1. public void addLast(PropertySource<?> propertySource) {  
  2.         if (logger.isDebugEnabled()) {  
  3.             logger.debug(String.format("Adding [%s] PropertySource with lowest search precedence",  
  4.                     propertySource.getName()));  
  5.         }  
  6.         removeIfPresent(propertySource);  
  7.         this.propertySourceList.add(propertySource);  
  8.     }  

其中removeIfPresent(propertySource)从字面意义中也可以看出为如果存在该PropertySource的话则从集合中删除数据:

[html] view plain copy
  1. protected void removeIfPresent(PropertySource<?> propertySource) {  
  2.         this.propertySourceList.remove(propertySource);  
  3.     }  

由于PropertySource中属性T泛型是不固定并对应内容也不固定,因此判断PropertySource在集合中的唯一性只能去看name,因此在PropertySource中重写equals,hashCode方法:

[html] view plain copy
  1. @Override  
  2.     public boolean equals(Object obj) {  
  3.         return (this == obj || (obj instanceof PropertySource &&  
  4.                 ObjectUtils.nullSafeEquals(this.name, ((PropertySource<?>) obj).name)));  
  5.     }  
  6.   
  7.     /**  
  8.      * Return a hash code derived from the {@code name} property  
  9.      * of this {@code PropertySource} object.  
  10.      */  
  11.     @Override  
  12.     public int hashCode() {  
  13.         return ObjectUtils.nullSafeHashCode(this.name);  
  14.     }  

从上可看出name标识PropertySource的唯一性。

至此StandardEnvironment的初始化完成.

创建Enviroment Bean

在bean中注入Enviroment实际为Enviroment接口的实现类,从类图中可以看出其子类颇多,具体在容器中是哪个子类就需要从代码获取答案。

在SpringApplication.run(String... args)中存在refresh(context)调用

[html] view plain copy
  1. protected void refresh(ApplicationContext applicationContext) {  
  2.         Assert.isInstanceOf(AbstractApplicationContext.class, applicationContext);  
  3.         ((AbstractApplicationContext) applicationContext).refresh();  
  4.     }  

实际调用AbstractApplicationContext中的refresh方法,在refresh方法调用prepareBeanFactory(beanFactory),其实现如下:

[html] view plain copy
  1. protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {  
  2.          ...  
  3.   
  4.         // Register default environment beans.  
  5.         if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {  
  6.             beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());  
  7.         }  
  8.         if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {  
  9.             beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());  
  10.         }  
  11.         if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {  
  12.             beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());  
  13.         }  
  14.     }  
其中调用beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment())注册名称为environment的bean;

[html] view plain copy
  1. public ConfigurableEnvironment getEnvironment() {  
  2.         if (this.environment == null) {  
  3.             this.environment = createEnvironment();  
  4.         }  
  5.         return this.environment;  
  6.     }  
其中enviroment变量为前面创建StandardServletEnvironment;前后得到验证。


实战:动态加载资源

在实际项目中资源信息如果能够动态获取在修改线上产品配置时及其方便,下面来展示一个加载动态获取资源的案例,而不是加载写死的properties文件信息

首先构造PropertySource,然后将其添加到Enviroment中

构造PropertySource

[html] view plain copy
  1. package com.lkl.springboot.config;  
  2.   
  3. import java.text.SimpleDateFormat;  
  4. import java.util.Date;  
  5. import java.util.HashMap;  
  6. import java.util.Map;  
  7. import java.util.Random;  
  8. import java.util.concurrent.ConcurrentHashMap;  
  9. import java.util.concurrent.Executors;  
  10. import java.util.concurrent.ScheduledExecutorService;  
  11. import java.util.concurrent.TimeUnit;  
  12.   
  13. import org.slf4j.Logger;  
  14. import org.slf4j.LoggerFactory;  
  15. import org.springframework.core.env.MapPropertySource;  
  16.   
  17. public class DynamicPropertySource extends MapPropertySource {  
  18.   
  19.     private static Logger                   log       = LoggerFactory.getLogger(DynamicPropertySource.class);  
  20.   
  21.     private static ScheduledExecutorService scheduled = Executors.newScheduledThreadPool(1);  
  22.     static {  
  23.         scheduled.scheduleAtFixedRate(new Runnable() {  
  24.             @Override  
  25.             public void run() {  
  26.                 map = dynamicLoadMapInfo();  
  27.             }  
  28.   
  29.         }, 1, 10, TimeUnit.SECONDS);  
  30.     }  
  31.   
  32.     public DynamicPropertySource(String name) {  
  33.         super(name, map);  
  34.     }  
  35.   
  36.     private static Map<String, Object> map = new ConcurrentHashMap<String, Object>(64);  
  37.   
  38.     @Override  
  39.     public Object getProperty(String name) {  
  40.         return map.get(name);  
  41.     }  
  42.   
  43.     //动态获取资源信息  
  44.     private static Map<String, Object> dynamicLoadMapInfo() {  
  45.         //通过http或tcp等通信协议获取配置信息  
  46.         return mockMapInfo();  
  47.     }  
  48.   
  49.     private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");  
  50.   
  51.     private static Map<String, Object> mockMapInfo() {  
  52.         Map<String, Object> map = new HashMap<String, Object>();  
  53.         int randomData = new Random().nextInt();  
  54.         log.info("random data{};currentTime:{}", randomData, sdf.format(new Date()));  
  55.         map.put("dynamic-info", randomData);  
  56.         return map;  
  57.     }  
  58. }  

这里模拟动态获取配置信息;

添加到Enviroment

[html] view plain copy
  1. package com.lkl.springboot.config;  
  2.   
  3. import javax.annotation.PostConstruct;  
  4.   
  5. import org.springframework.beans.factory.annotation.Autowired;  
  6. import org.springframework.context.annotation.Configuration;  
  7. import org.springframework.core.env.AbstractEnvironment;  
  8.   
  9. /**  
  10.  * 加载动态配置信息  
  11.  *   
  12.  * @author liaokailin  
  13.  * @version $Id: DynamicConfig.java, v 0.1 2015年10月2日 下午11:12:44 liaokailin Exp $  
  14.  */  
  15. @Configuration  
  16. public class DynamicConfig {  
  17.     public static final String DYNAMIC_CONFIG_NAME = "dynamic_config";  
  18.   
  19.     @Autowired  
  20.     AbstractEnvironment        environment;  
  21.   
  22.     @PostConstruct  
  23.     public void init() {  
  24.         environment.getPropertySources().addFirst(new DynamicPropertySource(DYNAMIC_CONFIG_NAME));  
  25.     }  
  26.   
  27. }  

在看完前面的源码以后 上面的两段代码非常容易理解~~


archaius为开源的配置管理api,有兴趣的同学可研究一下: https://github.com/Netflix/archaius。


下一篇将讲解spring boot如何加载application.xml。


本文转自http://blog.csdn.net/liaokailin/article/details/48186331

阅读全文
0 0
原创粉丝点击