All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.mengweifeng.springsupport.PropertyConfig Maven / Gradle / Ivy

package com.mengweifeng.springsupport;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Properties;
import java.util.Set;

import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.stereotype.Component;

@Component
public class PropertyConfig extends PropertyPlaceholderConfigurer {
	private Properties properties;
	private Set keys;

	@Override
	protected Properties mergeProperties() throws IOException {
		properties = super.mergeProperties();
		keys = properties.keySet();
		return properties;
	}

	public String getProperty(String key) {
		String value = null;
		try {
			value = new String(properties.getProperty(key).getBytes("iso-8859-1"));
		} catch (Exception e) {
		}

		return value;
	}

	/**
	 * 前匹配查找
	 * 
	 * @param matchKey	待匹配的key
	 * @return 符合要求的结果集合[key,value]
	 */
	public List findProperty(final String matchKey) {
		if (matchKey == null || matchKey.isEmpty()) {
			return null;
		}
		List matchKeys = new ArrayList();
		for (Object objectKey : keys) {
			String key = objectKey.toString();
			if (key.startsWith(matchKey)) {
				matchKeys.add(key);
			}
		}
		Collections.sort(matchKeys, new Comparator() {
			@Override
			public int compare(String o1, String o2) {
				o1 = o1.replace(matchKey, "");
				o2 = o2.replace(matchKey, "");
				Integer i1 = null, i2 = null;
				try {
					i1 = Integer.valueOf(o1);
				} catch (NumberFormatException e) {
				}
				try {
					i2 = Integer.valueOf(o2);
				} catch (NumberFormatException e) {
				}
				if (i1 != null && i2 != null) {
					return i1.compareTo(i2);
				}
				return 0;
			}
		});
		List values = new ArrayList();
		for (String key : matchKeys) {
			String value = properties.getProperty(key);
			try {
				value = new String(value.getBytes("iso-8859-1"));
			} catch (UnsupportedEncodingException e) {
			}
			values.add(new String[] { key, value });
		}
		return values;
	}

	public static void main(String[] args) {
		PropertyConfig p = new PropertyConfig();
		Set keys = new HashSet();
		keys.add("redis1");
		keys.add("redis2");
		keys.add("redis3");
		keys.add("redis.group4");
		p.keys = keys;
		p.findProperty("redis");
	}
}