在一些代码工程没有用ivy,maven这些库文件管理工具,jar包要么和工程文件放在一起或是存在本地的目录中然后通过开发工具导入。还有一种就是库文件打包在中间件中,开发时需要引入,不方便用ivy,maven进行依赖管理,这时候可能就需要开发一个IntelliJ Idea插件自动的加入自定义的库到开发工程中。
关于如何进行IntelliJ Idea插件开发请参考 http://www.jetbrains.org/intellij/sdk/docs/welcome.html
IntelliJ Idea库分为全局库,项目库,模块库。
- 全局库:库信息记录在<User Home>/.IntelliJIdea/config/options/applicationLibraries.xml,全局库对所有项目都可以访问。
- 项目库:库文件的类只能在当前项目访问,库信息记录在项目的*.ipr文件或是.idea/libraries目录下的文件中。
- 模块库:库文件的类只能在当前模块访问,库信息记录在模块的*.iml文件中
包com.intellij.openapi.roots.libraries下面的类提供了项目库和jars相关的类或是接口。
示例:
定义ClasspathComputer类,获取要加入库的jars路径或是classes路径。
public class ClasspathComputer {
// 获取jar路径List
public static List<String> getClassRoot(String librariePath){
File file = new File(librariePath);
List<File> list = new ArrayList<File>();
if(file.exists()){
if(file.isFile()){
list.add(file);
}else{
getClassFile(file,list);
}
}
List<String> rltList = new ArrayList<String>();
for(int i=0;i<list.size();i++){
rltList.add(list.get(i).getAbsolutePath());
}
return rltList;
}
private static void getClassFile(File parent,List<File> list){
if(parent.exists()){
File[] files = parent.listFiles();
if(files.length > 0){
for(int i=0;i<files.length;i++){
File cfile = files[i];
if(cfile.isFile()){
if(cfile.getName().endsWith(".jar")){
list.add(cfile);
}
}else if(cfile.isDirectory()){
getClassFile(cfile,list);
}
}
}
}
}
}
增加库的方法:
// 加库的方法
public void addApplicationLibrary(Project project,String libraryName,List<String> classesRoots) {
final LibraryTable.ModifiableModel model = LibraryTablesRegistrar.getInstance().getLibraryTable(project).getModifiableModel();
LibraryEx library = (LibraryEx) model.getLibraryByName(libraryName);
// 库不存在创建新的
if(library == null){
library = (LibraryEx) model.createLibrary(libraryName);
}
// 库中已有的jar删除
final LibraryEx.ModifiableModelEx libraryModel = library.getModifiableModel();
String[] classRootUrls = libraryModel.getUrls(OrderRootType.CLASSES);
for(String classRootURL : classRootUrls){
libraryModel.removeRoot(classRootURL,OrderRootType.CLASSES);
}
// 加入新的jar
for (String root : classesRoots) {
// 注意jar格式jar:{path_to_jar}.jar!/
if(root.endsWith(".jar")){
libraryModel.addRoot(VirtualFileManager.constructUrl("jar",root+"!/"), OrderRootType.CLASSES);
}else{
libraryModel.addRoot(VirtualFileManager.constructUrl("file",root), OrderRootType.CLASSES);
}
}
// 提交库变更
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
libraryModel.commit();
model.commit();
}
});
// 向项目模块依赖中增加新增的库
Module[] modules = ModuleManager.getInstance(project).getModules();
for(Module module : modules){
if(ModuleRootManager.getInstance(module).getModifiableModel().findLibraryOrderEntry(library) == null){
ModuleRootModificationUtil.addDependency(module,library);
}
}
}
最终会在工程的.idea/librarys/目录下增加自定义库名的xml文件。
这里只是示例,利用库的操作API结合自己的需求可以开发出实用的功能,在开发团队中能够提高团队的效率。