Skip to content

Instantly share code, notes, and snippets.

@pfmiles
Created April 22, 2015 08:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pfmiles/333b262b37b2d33c0272 to your computer and use it in GitHub Desktop.
Save pfmiles/333b262b37b2d33c0272 to your computer and use it in GitHub Desktop.
动态classpath property文件扫描、加载实现
package test;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
/**
* ocean模块化插件加载、管理类, 均为静态方法
*
* @author pf-miles
* @since 2014-11-13
*/
@SuppressWarnings("unchecked")
public abstract class PluginModuleLoader {
private static final Map<String, List<String>> props = new HashMap<String, List<String>>();
static {
// 尝试加载所有classpath中插件的配置
try {
Enumeration<URL> reses = Thread.currentThread().getContextClassLoader().getResources("META-INF/ocean-ext.properties");
if (reses != null && reses.hasMoreElements()) {
while (reses.hasMoreElements()) {
PropertiesConfiguration conf = new PropertiesConfiguration();
URL url = reses.nextElement();
try {
conf.load(url.openStream(), "UTF-8");
for (PluginConf k : PluginConf.values()) {
if (k.isMultiValue()) {
List<String> vals = (List<String>) conf.getList(k.getKey());
if (vals != null && !vals.isEmpty()) {
List<String> multi = props.get(k.getKey());
if (multi == null) {
multi = new ArrayList<String>();
props.put(k.getKey(), multi);
}
multi.addAll(vals);
}
} else {
List<String> val = (List<String>) conf.getList(k.getKey());
if (val != null && !val.isEmpty()) {
if (val.size() > 1) throw new RuntimeException(
"Illegal module plugin config entry found: "
+ k.getKey()
+ ", multi-values are not allowed for this key.");
if (props.containsKey(k.getKey())) throw new RuntimeException(
"Illegal module plugin config entry found: "
+ k.getKey()
+ ", multi-values are not allowed for this key.");
props.put(k.getKey(), val);
}
}
}
} catch (ConfigurationException e) {
throw new RuntimeException("Illegal module plugin config file: " + url, e);
}
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* 从插件模块中找出所有的bean配置文件, 对应所有ocean-ext.properties文件中的'beans'属性配置
*/
public static String[] resolveAllPluginBeanConfigFiles() {
List<String> confs = props.get(PluginConf.beans.getKey());
if (confs == null) return null;
return confs.toArray(new String[confs.size()]);
}
/**
* 取得插件指定的httpListener的beanId
*/
public static String resolveHttpListenerName() {
List<String> p = props.get(PluginConf.httpListener.getKey());
return p == null ? null : p.get(0);
}
public static void main(String... args) {
System.out.println(props);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment