插件开发中需要保存一些属性、对象,保存的目的为下次打开idea能够读取到这些属性,在setting的设置面板经常用到这种保存方式
第一步:创建一个 StorageConfig 用于保存属性
package com.dongbao.core.config;
public class StorageConfig {
/**
* 鎵撳寘淇濆瓨浣嶇疆
* */
private String patchPath;
public String getPatchPath() {
return patchPath;
}
public void setPatchPath(String patchPath) {
this.patchPath = patchPath;
}
}
第二步:创建一个 State 用于注册到IDEA中,下面代码的精髓在 @State 注解中
package com.dongbao.core.config;
import com.intellij.openapi.components.PersistentStateComponent;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.components.State;
import com.intellij.openapi.components.Storage;
import com.intellij.util.xmlb.XmlSerializerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@State(name = "dhg-patch",storages = {
@Storage(value = "dhgPatch.xml")
})
public class MyState implements PersistentStateComponent<MyState> {
private StorageConfig config;
public static MyState getInstance(){
return ServiceManager.getService(MyState.class);
}
@Nullable
@Override
public MyState getState() {
return this;
}
@Override
public void loadState(@NotNull MyState myState) {
if (null == myState) {
return;
}
XmlSerializerUtil.copyBean(myState, this);
}
public StorageConfig getConfig() {
if (null == config) {
config = new StorageConfig();
config.setPatchPath("D:\\DHG-Patcher");
}
return config;
}
public void setConfig(StorageConfig config) {
this.config = config;
}
}
第三步:将 MyState 添加到 plugin.xml 中使用
<extensions defaultExtensionNs="com.intellij">
<applicationService serviceImplementation="com.dongbao.core.config.MyState"/>
</extensions>