栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

页面路由开发

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

页面路由开发

传递路径信息

根目录 build.gradle 引入 kotlin 插件

classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

主工程 build.gradle 添加 kotlin 依赖

apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'

android {
	// 传递路径信息
    kapt {
        arguments {
            arg('root_project_dir', rootProject.projectDir.absolutePath)
        }
    }
}

dependencies {
	kapt project(':router-processor')
	implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
}
注解生成 json 文件

router-processor build.gradle 添加 gson 库依赖

implementation 'com.google.code.gson:gson:2.8.6'

将解析到的路由信息封装成json,然后写入到本地文件目录

	@AutoService(Processor.class)
public class DestinationProcessor extends AbstractProcessor {
    private static final String TAG = "DestinationProcessor";

    @Override
    public boolean process(Set set, RoundEnvironment roundEnvironment) {
     	String rootDir = processingEnv.getOptions().get("root_project_dir");
     	final JsonArray destinationJsonArray = new JsonArray();
     	// 遍历所有 @Destination 注解信息
  	    for (Element element : elements) {
  	    	 // 获取添加了注解类的信息
            Destination annotation = typeElement.getAnnotation(Destination.class);
            if (annotation==null) continue;
            // 获取添加的注解信息
            String url = annotation.url();
            String description = annotation.description();
            String realPath  = typeElement.getQualifiedName().toString(); // 获取添加注解的类名
  	    	 // 添加路由信息到jsonArray
            JsonObject jsonObject = new JsonObject();
            jsonObject.addProperty("url",url);
            jsonObject.addProperty("description",description);
            jsonObject.addProperty("realPath",realPath);
            destinationJsonArray.add(jsonObject);
  	    }
  	    // 写入 JSON 到本地文件中
        // 检测父目录是否存在
        File rootDirFile = new File(rootDir);
        if (!rootDirFile.exists()){
            throw new RuntimeException("root_project_dir not exist!");
        }

        // 创建 routet_mapping 目录
        File routerFileDir = new File(rootDirFile,"router_mapping");
        if (!routerFileDir.exists()){
            routerFileDir.mkdirs();
        }

        File mappingFile = new File(routerFileDir,"mapping_"+System.currentTimeMillis()+".json");

        // 写入json 路由信息到文件
        try{
            BufferedWriter out = new BufferedWriter(new FileWriter(mappingFile));
            out.write(destinationJsonArray.toString());
            out.flush();
            out.close();
        }catch (Throwable throwable){

        }
 }

buildSrc 插件工程读取传递的路径参数,并在每次构建任务之前对构建产物进行清理

	
class RouterPlugin implements Plugin {
    
    @Override
    void apply(Project project) {

        // 1. 自动帮助用户传递路径参数到注解处理器中
        if (project.extensions.findByName("kapt") !=null){
            project.extensions.findByName("kapt").arguments {
                arg("root_project_dir", project.rootProject.projectDir.absolutePath)
            }
        }

        // 2. 实现旧的构建产物自动清理
        project.clean.doFirst {
            // 删除上一次构建生成的 router_mapping 目录
            File routerMappingDir = new File(project.rootProject.projectDir,"router_mapping")
            if(routerMappingDir.exists()) {
                routerMappingDir.deleteDir()
            }
        }

        println "i am from RouterPlugin, apply from ${project.name}"

        // 为自定义插件添加扩展参数
        project.getExtensions().create('router',RouterExtension)
    }
}

每次构建的时候会自动扫描所有添加了注解的类,并自动以json格式写入到 指定目录中

生成页面文档
class RouterPlugin implements Plugin {

    @Override
    void apply(Project project) {
	  	project.afterevaluate {
	       RouterExtension extension =  project['router']
	
	            println("用户设置的WIKI路径为: ${extension.wikiDir}")
	
	            // 3. 在 javac 任务(compileDebugJavaWithJavaC) 后,汇总生成文档
	            project.tasks.findAll { task -> // 找到所有符合条件的 task
	                task.name.startsWith('compile') && task.name.endsWith('JavaWithJavac')
	            }.each { task ->
	                task.doLast {
	                    File routerMappingDir =  new File(project.rootProject.projectDir,'router_mapping')
	                    if (!routerMappingDir.exists()){
	                        return
	                    }
	                    File[] allChildFiles = routerMappingDir.listFiles()
	                    if (allChildFiles.length<1){
	                        return
	                    }
	                    StringBuilder markdownBuilder = new StringBuilder()
	                    markdownBuilder.append("# 页面文档nn")
	                    allChildFiles.each { child->
	                        if (child.name.endsWith('.json')) {
	                            JsonSlurper jsonSlurper = new JsonSlurper()
	                            def content = jsonSlurper.parse(child)
	
	                            content.each { innerContent ->
	                                def url = innerContent['url']
	                                def description = innerContent['description']
	                                def realPath = innerContent['realPath']
	
	                                markdownBuilder.append("## $description n")
	                                markdownBuilder.append("- url: $url n")
	                                markdownBuilder.append("- realPath: $realPath n")
	                            }
	                        }
	                    }
	                    File wikiFileDir = new File(extension.wikiDir)
	                    if (!wikiFileDir.exists()){
	                        wikiFileDir.mkdirs()
	                    }
	                    File wikiFile = new File(wikiFileDir,'页面文档.md')
	                    if (wikiFile.exists()){
	                        wikiFile.delete() // 删除旧数据
	                    }
	
	                    // 将汇总的 Router 信息写入到 MD
	                    wikiFile.write(markdownBuilder.toString())
	                }
	            }
	
	        }     
	
	    }
}					   
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/732340.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号