OSGI读取配置文件的方法

在OSGI框架下,通过Activator可以方便地获取配置文件。然而,在业务逻辑代码中直接读取配置文件则相对复杂。本文将探讨如何在业务方法中有效地访问配置文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值