import com.liming.tp.framework.util.PropertiesConfiguration;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.config.CacheConfiguration;
import org.apache.log4j.Logger;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import java.io.InputStream;
import java.util.Properties;
/**
* <b>
* Title:</b> 主题
* <br><b>
* Description:</b> 类功能描述
* <br><b>
* Copyright:</b> Copyright (c) 2013
* <br><b>
*
* @author tp-group
* @version 1.0
*/
public class InitActivator implements BundleActivator {
private static Logger logger = Logger.getLogger(InitActivator.class);
private static BundleContext context;
/**
* 获取Bundle上下文
* @return Bundle上下文
*/
public static BundleContext getContext() {
return context;
}
/*
* (non-Javadoc)
* @see org.osgi.tp.BundleActivator#start(org.osgi.tp.BundleContext)
*/
public void start(BundleContext bundleContext) throws Exception {
InitActivator.context = bundleContext;
Properties props = new Properties();
InputStream is = InitActivator.class.getResourceAsStream("/LMStart.configuration");
props.load(is);
PropertiesConfiguration.parseConfiguration(props);
CacheManager manager = new CacheManager(InitActivator.class.getResource("/mycache.xml"));
Cache cache = manager.getCache("mycache");
CacheConfiguration config = cache.getCacheConfiguration();
config.setTimeToIdleSeconds(60);
config.setTimeToLiveSeconds(120);
config.setMaxEntriesLocalHeap(10000);
config.setMaxEntriesLocalDisk(1000000);
}
/*
* (non-Javadoc)
* @see org.osgi.tp.BundleActivator#stop(org.osgi.tp.BundleContext)
*/
public void stop(BundleContext bundleContext) throws Exception {
InitActivator.context = null;
}
}
在osgi环境中,可以在activator中获得配置文件,方法如上。
但是在业务方法中,想获得文件,可不是那么容易的事情了,例如以下代码:
BusinessClass.class.getResourceAsStream("/LMStart.configuration");
此时会返回null,这是OSGI的classloader在作怪,此时唯一的好办法,就是这样:ExampleActivator.bundleContext.getBundle().getEntry(fileName)
通过Activator类的静态方法,获得bundleContext,再通过bundle的getEntry方法,就可以获得正确的URL。