spring读取配置文件优化

1、达到目的:根据tomcat的启动参数中配置不同的spring.profiles.active的值,读取不同环境的配置参数。

2、spring配置文件的代码:

<!-- 定义受环境影响易变的变量 -->
	<bean id="propertyPlaceholderConfigurer" class="com.zhou..spring.util.config.DynamicServerConfig">
		<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
		<property name="ignoreResourceNotFound" value="true" />
		<property name="locations">
			<list>
			    <value>classpath:config/system.devjunit.properties</value>
				<value>classpath:config/system.development.properties</value>
				<value>classpath:config/system.devzcb.properties</value>
				<value>classpath:config/system.development02.properties</value>
				<value>classpath:config/system.test.properties</value>
				<value>classpath:config/system.testzcb.properties</value>
				<value>classpath:config/system.test02.properties</value>
				<value>classpath:config/system.uat.properties</value>
				<value>classpath:config/system.uatzcb.properties</value>
				<value>classpath:config/system.uattask.properties</value>
				<value>classpath:config/system.run.properties</value>
				<value>classpath:config/system.runzcb.properties</value>
				<value>classpath:config/system.runtask.properties</value>
			</list>
		</property>
	</bean>
3、DynamicServerConfig类的代码:

public class DynamicServerConfig extends PropertyPlaceholderConfigurer {

	/**
	 * Set a location of a properties file to be loaded.
	 * <p>
	 * Can point to a classic properties file or to an XML file that follows JDK 1.5's properties XML format.
	 */
	private boolean localOverride = false;

	private Properties[] localProperties;

	private Resource[] locations;

	private final PropertiesPersister propertiesPersister = new DefaultPropertiesPersister();

	private boolean ignoreResourceNotFound = false;

	/**
	 * Set if failure to find the property resource should be ignored. True is appropriate if the properties file is
	 * completely optional. Default is "false".
	 */
	@Override
	public void setIgnoreResourceNotFound(boolean ignoreResourceNotFound) {
		this.ignoreResourceNotFound = ignoreResourceNotFound;
	}

	/**
	 * Set local properties, e.g. via the "props" tag in XML bean definitions. These can be considered defaults, to be
	 * overridden by properties loaded from files.
	 */
	@Override
	public void setProperties(Properties properties) {
		this.localProperties = new Properties[] { properties };
		super.setProperties(properties);
	}

	/**
	 * Set local properties, e.g. via the "props" tag in XML bean definitions, allowing for merging multiple properties
	 * sets into one.
	 */
	@Override
	public void setPropertiesArray(Properties[] propertiesArray) {
		this.localProperties = propertiesArray;
	}

	@Override
	public void setLocation(Resource location) {
		this.locations = new Resource[] { location };
		super.setLocation(location);
	}

	/**
	 * Set locations of properties files to be loaded.
	 * <p>
	 * Can point to classic properties files or to XML files that follow JDK 1.5's properties XML format.
	 */

	@Override
	public void setLocations(Resource[] locations) {
		this.locations = locations;
		super.setLocations(locations);
	}

	/**
	 * Set whether local properties override properties from files. Default is "false": properties from files override
	 * local defaults. Can be switched to "true" to let local properties override defaults from files.
	 */
	@Override
	public void setLocalOverride(boolean localOverride) {
		this.localOverride = localOverride;
	}

	@Override
	public Properties mergeProperties() throws IOException {
		Properties result = new Properties();

		if (this.localOverride) {
			// Load properties from file upfront, to let local properties
			// override.
			loadProperties(result);
		}

		if (this.localProperties != null) {
			for (int i = 0; i < this.localProperties.length; i++) {
				CollectionUtils.mergePropertiesIntoMap(this.localProperties[i], result);
			}
		}

		if (!this.localOverride) {
			// Load properties from file afterwards, to let those properties
			// override.
			loadProperties(result);
		}

		return result;
	}

	/**
	 * Load properties into the given instance.
	 * 
	 * @param props
	 *            the Properties instance to load into
	 * @throws java.io.IOException
	 *             in case of I/O errors
	 * @see #setLocations
	 */
	@Override
	protected void loadProperties(Properties props) throws IOException {

		if (this.locations != null) {
			for (int i = 0; i < this.locations.length; i++) {
				Resource location = this.locations[i];
				if (logger.isInfoEnabled()) {
					logger.info("Loading properties file from " + location);
				}
				InputStream is = null;
				try {
					/**
					 * 读取启动参数中的环境变量,默认为devjunit
					 */
					String runEnv = System.getProperty("spring.profiles.active", "devjunit");
					if (location.getFilename().indexOf("." + runEnv + ".") > 0) {
						is = location.getInputStream();
						this.propertiesPersister.load(props, is);
						break;
					}

				} catch (IOException ex) {
					if (this.ignoreResourceNotFound) {
						if (logger.isWarnEnabled()) {
							logger.warn("Could not load properties from " + location + ": " + ex.getMessage());
						}
					} else {
						throw ex;
					}
				} finally {
					if (is != null) {
						is.close();
					}
				}
			}
		}
	}

}

4、然后添加不同环境下的配置文件,便于减少因调整配置文件导致的失误。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值