天天看点

Eclipse插件开发-首选项存储方案(IPreferenceStore)

IPreferenceStore有三个具体实现,分别是

  • ChainedPreferenceStore 链式存储
  • PreferenceStore 基于文件存储
  • ScopedPreferenceStore 基于范围存储

ScopedPreferenceStore 基于范围存储

  • 实例化
  • instance scope按照工作空间或平台的运行实例存储的,每个运行实例所存储的值可能是不一样的,不同实例之间只使用自己的值,无法与其它实例共享。

    存储位置位于运行实例的如下位置:{workspace_path}.metadata.plugins\org.eclipse.core.runtime.settings{qualifier}.prefs

  • configuration scope 各个工作空间将共享它们。例如,如果用户具有平台的单个安装,但是运行几个不同的工作空间,则配置级别范围的首选项将在工作空间之间共享。

    存储位置位于程序安装目录的如下位置:{configuration}.settings{qualifier}.prefs

  • Default scope-表示首选项的缺省值。它们不是由平台更改或存储的。但是,这些值来源于随插件的产品或主要功能部件一起存储的文件。
  • 加载首选项配置
try {
  preferenceStore.load();
} catch (IOException e) {
  logger.error("首选项加载异常", e);
}
           

PreferenceStore 基于文件存储

  • 实例化
PreferenceStore preferenceStore=new PreferenceStore(storePath);
           
  • storePath 首选项存储文件路径
  • 加载同ScopedPreferenceStore
ChainedPreferenceStore 不常用,在这不再描述

PreferenceStore在Ecllipse插件Activator中应用的源码

  • Activator类中覆盖默认首选项存储方案
private PreferenceStore preferenceStore;
    @Override
	public IPreferenceStore getPreferenceStore() {
		// Create the preference store lazily.
		if (preferenceStore == null) {
			// InstanceScope.INSTANCE added in 3.7
			//preferenceStore = new ScopedPreferenceStore(InstanceScope.INSTANCE, PLUGIN_ID);
			String storePath=IDEUtils.getPreferenceStorePath(getBundle().getSymbolicName()+Constants.CONFIG_PREFERENCE_STORE_SUFFIX);
			preferenceStore=new PreferenceStore(storePath);
			initializeDefaultPreferences(preferenceStore);
			try {
				//if(IoTools.)
				preferenceStore.load();
			} catch (IOException e) {
				logger.error("首选项加载异常", e);
			}
		}
		return preferenceStore;
	}

	@Override
	protected void initializeDefaultPreferences(IPreferenceStore store) {
		store.setDefault("plugin.name", "wy2-tool-suite");
		//super.initializeDefaultPreferences(store);
		
	}
	
	@Override
	protected void savePreferenceStore() {
		//super.savePreferenceStore();
		if (preferenceStore != null) {
			try {
				this.preferenceStore.save();
			} catch (IOException e) {
				logger.error("首选项保存异常", e);
			}
		}
	}

           
  • 读取、修改保存
IPreferenceStore iPreferenceStore =Activator.getDefault().getPreferenceStore();	
iPreferenceStore.setValue("plugin.name", "wy2-tool-suite3");
if(iPreferenceStore.needsSaving()) {
  savePreferenceStore();
}
logger.info("plugin.name: {}",iPreferenceStore.getString("plugin.name"));
           

继续阅读