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。