Paoding Rose源码分析1-读取Rose配置文件

Paoding Rose是人人网公司做的一个开源的类似于Spring的Java框架,支持类似于Spring和MVC,ORM,数据库分表操作,给予Spring2.X

本文,研究下RoseAppContext如何读取配置文件,以及配置文件的命名是哪种约定方式

package com.xxx.rose.scanning;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;

import net.paoding.rose.scanning.ResourceRef;
import net.paoding.rose.scanning.RoseScanner;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.core.io.support.ResourcePatternResolver;

public class RoseSettings {

	protected static Log logger = LogFactory.getLog(RoseSettings.class);

	public static Properties findSettingsProperties() {
		if (logger.isInfoEnabled()) {
			logger.info("[applicationContext] start to find settings properties ...");
		}

		List<Resource> properties = new ArrayList<Resource>();
		ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();

		try {
			List<ResourceRef> resources = RoseScanner.getInstance()
					.getJarResources();
			for (ResourceRef ref : resources) {
				Resource[] founds = ref.getInnerResources(resourcePatternResolver,
						"settings*.properties");
				properties.addAll(Arrays.asList(founds));
			}
			resources = RoseScanner.getInstance().getClassesFolderResources();

			for (ResourceRef ref : resources) {
				Resource[] founds = ref.getInnerResources(resourcePatternResolver,
						"settings*.properties");
				properties.addAll(Arrays.asList(founds));
			}
		} catch (IOException e) {
			throw new RuntimeException(e);
		}

		int index = 0;
		Resource settings = null;
		Properties props = new Properties();
		for (Resource resource : properties) {
			try {
				if ("settings.properties".equals(resource.getFilename()))
					settings = resource;

				PropertiesLoaderUtils.fillProperties(props, resource);
				index++;
			} catch (IOException e) {
				logger.error("Load properties file fail : " + resource);
			}
		}

		try {
			if (settings != null)
				PropertiesLoaderUtils.fillProperties(props, settings);
		} catch (IOException e) {
			logger.warn("Load settings.properties fail : " + settings);
		}

		if (logger.isInfoEnabled()) {
			logger.info("[applicationContext] FOUND " + index + " properties files");
			if (settings != null)
				logger.info("[applicationContext] FOUND settings.properties: " + settings);
		}
		if (logger.isDebugEnabled()) {
			logger.debug("[applicationContext] FOUND settings : " + props);
		}
		return props;
	}
}

RoseAppContext.java

/*
* Copyright 2007-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.paoding.rose.scanning.context;

import java.io.IOException;

import net.paoding.rose.scanning.LoadScope;
import net.paoding.rose.scanning.context.core.RoseResources;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextException;
import org.springframework.context.annotation.AnnotationConfigUtils;
import org.springframework.context.support.AbstractXmlApplicationContext;
import org.springframework.core.io.Resource;

import com.jingwei.rose.scanning.RoseSettings;

/**
 * 
 * @author 王志亮 [qieqie.wang@gmail.com]
 * @author han.liao [in355hz@gmail.com]
 * 
 */
public class RoseAppContext extends AbstractXmlApplicationContext {

    private Log logger = LogFactory.getLog(getClass());

    private String[] scopeValues;

    public RoseAppContext() {
        this("", true);
    }

    public RoseAppContext(String scope, boolean refresh) {
        this(new LoadScope(scope, "applicationContext"), refresh);
    }

    public RoseAppContext(LoadScope scope, boolean refresh) {
        this.scopeValues = scope.getScope("applicationContext");
        logger.info("create a RoseAppContext, with scope='" + scope + "'");
        if (refresh) {
            refresh();
        }
    }

    /**
     * 返回对应类型的唯一 Bean, 包括可能的祖先 {@link ApplicationContext} 中对应类型的 Bean.
     * 
     * @param beanType - Bean 的类型
     * 
     * @throws BeansException
     */
    public <T> T getBean(Class<T> beanType) throws BeansException {
        return beanType.cast(BeanFactoryUtils.beanOfTypeIncludingAncestors(this, beanType));
    }

    @Override
    protected final Resource[] getConfigResources() {
        try {
            return getConfigResourcesThrowsIOException();
        } catch (IOException e) {
            throw new ApplicationContextException("getConfigResources", e);
        }
    }

    protected Resource[] getConfigResourcesThrowsIOException() throws IOException {
        return RoseResources.findContextResources(this.scopeValues).toArray(new Resource[0]);
    }

    @Override
    protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
        prepareBeanFactoryByRose(beanFactory);
        super.prepareBeanFactory(beanFactory);
    }

    /** Rose对BeanFactory的特殊处理,必要时可以覆盖这个方法去掉Rose的特有的处理 */
    protected void prepareBeanFactoryByRose(ConfigurableListableBeanFactory beanFactory) {
        beanFactory.registerSingleton("settings", RoseSettings.findSettingsProperties());
        BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
        AnnotationConfigUtils.registerAnnotationConfigProcessors(registry);
    }

    public RoseAppContext getApplicationContext() {
        return this;
    }

}

此类重写了Sring 的AbstractXmlApplicationContext的 prepareBeanFactory方法

----->

prepareBeanFactoryByRose
-->RoseSettings.findSettingsPropertie

RoseSettings.java  包含了RoseSettings.findSettingsPropertie的实现

package com.xxx.rose.scanning;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;

import net.paoding.rose.scanning.ResourceRef;
import net.paoding.rose.scanning.RoseScanner;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.core.io.support.ResourcePatternResolver;

public class RoseSettings {

	protected static Log logger = LogFactory.getLog(RoseSettings.class);

	public static Properties findSettingsProperties() {
		if (logger.isInfoEnabled()) {
			logger.info("[applicationContext] start to find settings properties ...");
		}

		List<Resource> properties = new ArrayList<Resource>();
		ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();

		try {
			List<ResourceRef> resources = RoseScanner.getInstance()
					.getJarResources();
			for (ResourceRef ref : resources) {
				Resource[] founds = ref.getInnerResources(resourcePatternResolver,
						"settings*.properties");
				properties.addAll(Arrays.asList(founds));
			}
			resources = RoseScanner.getInstance().getClassesFolderResources();

			for (ResourceRef ref : resources) {
				Resource[] founds = ref.getInnerResources(resourcePatternResolver,
						"settings*.properties");
				properties.addAll(Arrays.asList(founds));
			}
		} catch (IOException e) {
			throw new RuntimeException(e);
		}

		int index = 0;
		Resource settings = null;
		Properties props = new Properties();
		for (Resource resource : properties) {
			try {
				if ("settings.properties".equals(resource.getFilename()))
					settings = resource;

				PropertiesLoaderUtils.fillProperties(props, resource);
				index++;
			} catch (IOException e) {
				logger.error("Load properties file fail : " + resource);
			}
		}

		try {
			if (settings != null)
				PropertiesLoaderUtils.fillProperties(props, settings);
		} catch (IOException e) {
			logger.warn("Load settings.properties fail : " + settings);
		}

		if (logger.isInfoEnabled()) {
			logger.info("[applicationContext] FOUND " + index + " properties files");
			if (settings != null)
				logger.info("[applicationContext] FOUND settings.properties: " + settings);
		}
		if (logger.isDebugEnabled()) {
			logger.debug("[applicationContext] FOUND settings : " + props);
		}
		return props;
	}
}

可以看出Rose只会读取jar,还有classes路径下的settings*.properties文件中的配置信息

所以,配置文件  settings.properties文件内容可以是如下

jade.datasource=datasource-mobile.yaml
redis.conf.password=pwd


 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值