---
title: "Struts2--Dispatcher&ConfigurationProvider续"
author: "mujun1209"
date: "2010-10-26T16:36:46Z"
tags: ["Apache", "Bean", "Struts", "Web", "XML"]
categories: ["企业架构"]
slug: "struts2-dispatcher-configurationprovider"
draft: false
lastmod: "2010-10-26T16:36:46Z"
id: 794646
url: "https://mujun1209.iteye.com/blog/794646"
---

接下来第三步:init\_LegacyStrutsProperties()  
调用的是调用的是LegacyPropertiesConfigurationProvider  
通过比较前面DefaultPropertiesProvider与调用的是LegacyPropertiesConfigurationProvider.  
发现DefaultPropertiesProvider继承自后者,但重写了register()方法,主要是生成PropertiesSetting的不同,前者是根据org/apache/struts2/default.properties  
后者是根据struts.properties  
我们展开register()中的Settings.getInstance(),最后是调用getDefaultInstance()

Java代码 [![复制代码](http://qidaoxp.iteye.com/images/icon_copy.gif)](http://qidaoxp.iteye.com/blog/497052 "复制代码")

01. **private** **static** Settings getDefaultInstance() {
02. **if** (defaultImpl == **null**) {
03. // Create bootstrap implementation
04. //不带参数的DefaultSettings(),区别与DefaultPropertiesProvider中直接带default.properties参数
05. //不带参数就是默认为struts.propertes,并且加载struts.custom.properties所定义的properties文件
06. defaultImpl = **new** DefaultSettings();
07. // Create default implementation
08. **try** {
09. //STRUTS\_CONFIGURATION为:struts.configuration
10. //在struts.proterties中查找struts.configuration的值,这个值必须是org.apache.struts2.config.Configuration接口的实现类
11. //所以我有个困惑就是在下面的转换当中怎么将Configuration转换成Setting类型的...
12. //这一点先放下了,有时间再研究
13. String className = get(StrutsConstants.STRUTS\_CONFIGURATION);
14. **if** (!className.equals(defaultImpl.getClass().getName())) {
15. **try** {
16. // singleton instances shouldn't be built accessing request or session-specific context data
17. defaultImpl = (Settings) ObjectFactory.getObjectFactory().buildBean(Thread.currentThread().getContextClassLoader().loadClass(className), **null**);
18. } **catch** (Exception e) {
19. LOG.error("Settings: Could not instantiate the struts.configuration object, substituting the default implementation.", e);
20. }
21. }
22. } **catch** (IllegalArgumentException ex) {
23. // ignore

```
    private static Settings getDefaultInstance() {
        if (defaultImpl == null) {
            // Create bootstrap implementation
			//不带参数的DefaultSettings(),区别与DefaultPropertiesProvider中直接带default.properties参数
			//不带参数就是默认为struts.propertes,并且加载struts.custom.properties所定义的properties文件
            defaultImpl = new DefaultSettings();

            // Create default implementation
            try {
			    //STRUTS_CONFIGURATION为:struts.configuration
				//在struts.proterties中查找struts.configuration的值,这个值必须是org.apache.struts2.config.Configuration接口的实现类
				//所以我有个困惑就是在下面的转换当中怎么将Configuration转换成Setting类型的...
				//这一点先放下了,有时间再研究
                String className = get(StrutsConstants.STRUTS_CONFIGURATION);

                if (!className.equals(defaultImpl.getClass().getName())) {
                    try {
                        // singleton instances shouldn't be built accessing request or session-specific context data
                        defaultImpl = (Settings) ObjectFactory.getObjectFactory().buildBean(Thread.currentThread().getContextClassLoader().loadClass(className), null);
                    } catch (Exception e) {
                        LOG.error("Settings: Could not instantiate the struts.configuration object, substituting the default implementation.", e);
                    }
                }
            } catch (IllegalArgumentException ex) {
                // ignore
           
```

 

在2.1.6中去掉了第四步:init\_ZeroConfiguration();  
第五步是自定义的configProviders

Java代码 [![复制代码](http://qidaoxp.iteye.com/images/icon_copy.gif)](http://qidaoxp.iteye.com/blog/497052 "复制代码")

01. **private** **void** init\_CustomConfigurationProviders() {
02. //从这里可以看到可以将自定义的Provider定义在web.xml中FilterDispatcher的param中:configProviders
03. String configProvs = initParams.get("configProviders");
04. **if** (configProvs != **null**) {
05. String\[] classes = configProvs.split("\\\\s\*\[,]\\\\s\*");
06. **for** (String cname : classes) {
07. **try** {
08. Class cls = ClassLoaderUtils.loadClass(cname, **this**.getClass());
09. ConfigurationProvider prov = (ConfigurationProvider)cls.newInstance();
10. configurationManager.addConfigurationProvider(prov);
11. }
12. ...
13. }
14. }
15. }

```
    private void init_CustomConfigurationProviders() {
        //从这里可以看到可以将自定义的Provider定义在web.xml中FilterDispatcher的param中:configProviders
        String configProvs = initParams.get("configProviders");
        if (configProvs != null) {
            String[] classes = configProvs.split("\\s*[,]\\s*");
            for (String cname : classes) {
                try {
                    Class cls = ClassLoaderUtils.loadClass(cname, this.getClass());
                    ConfigurationProvider prov = (ConfigurationProvider)cls.newInstance();
                    configurationManager.addConfigurationProvider(prov);
                } 
				...
            }
        }
    }
```

 

第六步:init\_FilterInitParameters

Java代码 [![复制代码](http://qidaoxp.iteye.com/images/icon_copy.gif)](http://qidaoxp.iteye.com/blog/497052 "复制代码")

01. //从这里可以看出struts.properties中的属性不仅可以在struts.xml中以constant形式定义,而且可以在FilterDispatcher的param中定义
02. **private** **void** init\_FilterInitParameters() {
03. configurationManager.addConfigurationProvider(**new** ConfigurationProvider() {
04. **public** **void** destroy() {}
05. **public** **void** init(Configuration configuration) **throws** ConfigurationException {}
06. **public** **void** loadPackages() **throws** ConfigurationException {}
07. **public** **boolean** needsReload() { **return** **false**; }
08. **public** **void** register(ContainerBuilder builder, LocatableProperties props) **throws** ConfigurationException {
09. props.putAll(initParams);//在这里实现滴~
10. }
11. });
12. }

```
//从这里可以看出struts.properties中的属性不仅可以在struts.xml中以constant形式定义,而且可以在FilterDispatcher的param中定义	
    private void init_FilterInitParameters() {
        configurationManager.addConfigurationProvider(new ConfigurationProvider() {
            public void destroy() {}
            public void init(Configuration configuration) throws ConfigurationException {}
            public void loadPackages() throws ConfigurationException {}
            public boolean needsReload() { return false; }

            public void register(ContainerBuilder builder, LocatableProperties props) throws ConfigurationException {
                props.putAll(initParams);//在这里实现滴~
            }
        });
    }	
```

 

第七步:init\_AliasStandardObjects,使用BeanSelectionProvider  
这是将配置文件中定义的&lt;bean&gt;与实际的类相映射,就是注入bean的依赖关系,这部分以后有时候再研究Container  
   
接下来是看怎样调用这些ConfigurationProviders  
展开init\_PreloadConfiguration()

Java代码 [![复制代码](http://qidaoxp.iteye.com/images/icon_copy.gif)](http://qidaoxp.iteye.com/blog/497052 "复制代码")

01. **private** Container init\_PreloadConfiguration() {
02. Configuration config = configurationManager.getConfiguration();
03. Container container = config.getContainer();
04. **boolean** reloadi18n = Boolean.valueOf(container.getInstance(String.**class**, StrutsConstants.STRUTS\_I18N\_RELOAD));
05. LocalizedTextUtil.setReloadBundles(reloadi18n);
06. **return** container;
07. }
08. //再看getConfiguration()
09. **public** **synchronized** Configuration getConfiguration() {
10. **if** (configuration == **null**) {
11. setConfiguration(**new** DefaultConfiguration(defaultFrameworkBeanName));
12. **try** {
13. //重点就是这个reloadContainer
14. configuration.reloadContainer(getContainerProviders());
15. } **catch** (ConfigurationException e) {
16. setConfiguration(**null**);
17. **throw** **new** ConfigurationException("Unable to load configuration.", e);
18. }
19. } **else** {
20. conditionalReload();
21. }
22. **return** configuration;
23. }

```
    private Container init_PreloadConfiguration() {
        Configuration config = configurationManager.getConfiguration();
        Container container = config.getContainer();

        boolean reloadi18n = Boolean.valueOf(container.getInstance(String.class, StrutsConstants.STRUTS_I18N_RELOAD));
        LocalizedTextUtil.setReloadBundles(reloadi18n);

        return container;
    }
         //再看getConfiguration()
    public synchronized Configuration getConfiguration() {
        if (configuration == null) {
            setConfiguration(new DefaultConfiguration(defaultFrameworkBeanName));
            try {
			//重点就是这个reloadContainer
                configuration.reloadContainer(getContainerProviders());
            } catch (ConfigurationException e) {
                setConfiguration(null);
                throw new ConfigurationException("Unable to load configuration.", e);
            }
        } else {
            conditionalReload();
        }

        return configuration;
    }
```

 

展开DefaultConfiguration中的reloadContainer

Java代码 [![复制代码](http://qidaoxp.iteye.com/images/icon_copy.gif)](http://qidaoxp.iteye.com/blog/497052 "复制代码")

01. **public** **synchronized** List&lt;PackageProvider&gt; reloadContainer(List&lt;ContainerProvider&gt; providers) **throws** ConfigurationException {
02. packageContexts.clear();
03. loadedFileNames.clear();
04. List&lt;PackageProvider&gt; packageProviders = **new** ArrayList&lt;PackageProvider&gt;();
05. //Struts2(xwork2)用Container来完成依赖注入的功能
06. //首先初始化一个ContainerBuilder,再由builder来保存接口与实现类或工厂类的对应关系
07. //然后通过builder.create(boolean)方法产生container
08. //由container.getInstance(Class);就可以得到接口的实现实例了
09. //这一部分比较复杂,后面研究完成了,会单独拿出来讲,这里先弄清楚Xwork依赖注入的实现步骤就可以了
10. ContainerProperties props = **new** ContainerProperties();
11. ContainerBuilder builder = **new** ContainerBuilder();
12. **for** (**final** ContainerProvider containerProvider : providers)
13. {
14. //循环调用ConfigurationProvider的init和register方法,明白了吧,在这里统一循环调用
15. containerProvider.init(**this**);
16. containerProvider.register(builder, props);
17. }
18. props.setConstants(builder);
19. //注入依赖关系,在这里并不产生实例
20. builder.factory(Configuration.**class**, **new** Factory&lt;Configuration&gt;() {
21. **public** Configuration create(Context context) **throws** Exception {
22. **return** DefaultConfiguration.**this**;
23. }
24. });
25. ActionContext oldContext = ActionContext.getContext();
26. **try** {
27. // Set the bootstrap container for the purposes of factory creation
28. Container bootstrap = createBootstrapContainer();
29. setContext(bootstrap);
30. //create已经注入依赖关系的Container
31. container = builder.create(**false**);
32. setContext(container);
33. objectFactory = container.getInstance(ObjectFactory.**class**);
34. // Process the configuration providers first
35. **for** (**final** ContainerProvider containerProvider : providers)
36. {
37. **if** (containerProvider **instanceof** PackageProvider) {
38. container.inject(containerProvider);
39. //调用PackageProvider的loadPackages()方法,这里主要是针对XmlConfigurationProvider和StrutsXmlConfigurationProvider
40. ((PackageProvider)containerProvider).loadPackages();
41. packageProviders.add((PackageProvider)containerProvider);
42. }
43. }
44. // Then process any package providers from the plugins
45. Set&lt;String&gt; packageProviderNames = container.getInstanceNames(PackageProvider.**class**);
46. **if** (packageProviderNames != **null**) {
47. **for** (String name : packageProviderNames) {
48. PackageProvider provider = container.getInstance(PackageProvider.**class**, name);
49. provider.init(**this**);
50. provider.loadPackages();
51. packageProviders.add(provider);
52. }
53. }
54. rebuildRuntimeConfiguration();
55. } **finally** {
56. **if** (oldContext == **null**) {
57. ActionContext.setContext(**null**);
58. }
59. }
60. **return** packageProviders;
61. }

```
    public synchronized List<PackageProvider> reloadContainer(List<ContainerProvider> providers) throws ConfigurationException {
        packageContexts.clear();
        loadedFileNames.clear();
        List<PackageProvider> packageProviders = new ArrayList<PackageProvider>();

		//Struts2(xwork2)用Container来完成依赖注入的功能
		//首先初始化一个ContainerBuilder,再由builder来保存接口与实现类或工厂类的对应关系
		//然后通过builder.create(boolean)方法产生container
		//由container.getInstance(Class);就可以得到接口的实现实例了
		//这一部分比较复杂,后面研究完成了,会单独拿出来讲,这里先弄清楚Xwork依赖注入的实现步骤就可以了
        ContainerProperties props = new ContainerProperties();
        ContainerBuilder builder = new ContainerBuilder();
        for (final ContainerProvider containerProvider : providers)
        {
		    //循环调用ConfigurationProvider的init和register方法,明白了吧,在这里统一循环调用
            containerProvider.init(this);
            containerProvider.register(builder, props);
        }
        props.setConstants(builder);
        //注入依赖关系,在这里并不产生实例
        builder.factory(Configuration.class, new Factory<Configuration>() {
            public Configuration create(Context context) throws Exception {
                return DefaultConfiguration.this;
            }
        });

        ActionContext oldContext = ActionContext.getContext();
        try {
            // Set the bootstrap container for the purposes of factory creation
            Container bootstrap = createBootstrapContainer();
            setContext(bootstrap);
			//create已经注入依赖关系的Container
            container = builder.create(false);
            setContext(container);
            objectFactory = container.getInstance(ObjectFactory.class);

            // Process the configuration providers first
            for (final ContainerProvider containerProvider : providers)
            {
                if (containerProvider instanceof PackageProvider) {
                    container.inject(containerProvider);
					//调用PackageProvider的loadPackages()方法,这里主要是针对XmlConfigurationProvider和StrutsXmlConfigurationProvider
                    ((PackageProvider)containerProvider).loadPackages();
                    packageProviders.add((PackageProvider)containerProvider);
                }
            }

            // Then process any package providers from the plugins
            Set<String> packageProviderNames = container.getInstanceNames(PackageProvider.class);
            if (packageProviderNames != null) {
                for (String name : packageProviderNames) {
                    PackageProvider provider = container.getInstance(PackageProvider.class, name);
                    provider.init(this);
                    provider.loadPackages();
                    packageProviders.add(provider);
                }
            }

            rebuildRuntimeConfiguration();
        } finally {
            if (oldContext == null) {
                ActionContext.setContext(null);
            }
        }
        return packageProviders;
    }	
```