一、背景
框架:OSGI(由felix框架实现)
需求:读取静态配置文件*.properties
二、问题:由于OSGI的运行机制,导致bundle中的普通类无法正常读取静态配置文件,只能在<Bundle-Activator>Activator.class</Bundle-Activator>声明的初始化类中才能获取,bundle中其他类获取静态文件会报空指针。
三、解决方案:
3.1 静态文件位置:
bundle打包插件(maven-bundle-plugin)默认的静态文件位置是main目录下的resources(不能拼错,s也不能少),这样编译完后静态文件才会被打包进去,打包完后注意检查。
3.2 代码
注解是felix框架的,重点是ComponentContext 这个接口,通过BundleContext可以获取静态文件
@Activate
public void activate(ComponentContext context) { }
URL configUrl= context.getBundleContext().getBundle().getResource(filename);
InputStream is = configUrl.openStream();
Properties properties = new Properties();
properties.load(is);