vue3 -- @vue/compiler-sfc 单文件转换工具

@vue/compiler-sfc

"version": "3.2.37"

SFC是vue中重要的一环,也是vue3中对于静态节点进行缓存提升的重要位置

SFC -- single file Component 单文件组件,以 .vue 进行结尾,这个文件浏览器也不会识别,最终也是要被转换成js代码

SFC中包含三块,template、script、style等三块代码,分别表示模版、脚本、样式三块

@vue/compiler-sfc的作用就是把单文件组件编译成为js代码

parse

下面就看一看具体的使用

新建一个Foo.vue组件

<template>
    <input type="text" v-model="name">
</template>
<script lang='ts'>
import { defineComponent, ref } from 'vue'
export default defineComponent({
    name: 'foo',
    setup() {
        return {
            name: ref('jack')
        }
    }
})
</script>
<style lang="scss">
input {
    color: #333;
}
</style>

组件同时包括templatescriptstyle三块

新建一个nodejs脚本

const { parse } = require("@vue/compiler-sfc")
const fs = require("fs")
fs.readFile("./foo.vue", (err, data) => {

    let parsed = parse(data.toString(), {
        filename: 'foo.vue'
    })
    console.log('parsed', parsed);

})

用fs读取到文件的内容后,使用parse解析, 最终会返回一个对象

{
  descriptor: {
    filename: 'foo.vue',
    source: '<template>\n' +
      '    <input type="text" v-model="name">\n' +
      '</template>\n' +
      "<script lang='ts'>\n" +
      "import { defineComponent, ref } from 'vue'\n" +
      'export default defineComponent({\n' +
      "    name: 'foo',\n" +
      '    setup() {\n' +
      '        return {\n' +
      "            name: ref('jack')\n" +
      '        }\n' +
      '    }\n' +
      '})\n' +
      '</script>\n' +
      '<style lang="scss">\n' +
      'input {\n' +
      '    color: #333;\n' +
      '}\n' +
      '</style>\n',
    template: {
      type: 'template',
      content: '\n    <input type="text" v-model="name">\n',
      loc: [Object],
      attrs: {},
      ast: [Object],
      map: [Object]
    },
    script: {
      type: 'script',
      content: '\n' +
        "import { defineComponent, ref } from 'vue'\n" +
        'export default defineComponent({\n' +
        "    name: 'foo',\n" +
        '    setup() {\n' +
        '        return {\n' +
        "            name: ref('jack')\n" +
        '        }\n' +
        '    }\n' +
        '})\n',
      loc: [Object],
      attrs: [Object],
      lang: 'ts',
      map: [Object]
    },
    scriptSetup: null,
    styles: [ [Object] ],
    customBlocks: [],
    cssVars: [],
    slotted: false,
    shouldForceReload: [Function: shouldForceReload]
  },
  errors: []
}

setup脚本改造foo.vue

<template>
    <input type="text" v-model="name">
</template>
<script lang='ts' setup>
import { ref } from 'vue'

const name = ref('jack');
</script>
<style lang="scss">
input {
    color: #333;
}
</style>

setup语法编译后的结果

{
  descriptor: {
    filename: 'foo.vue',
    source: '<template>\n' +
      '    <input type="text" v-model="name">\n' +
      '</template>\n' +
      "<script lang='ts' setup>\n" +
      "import { ref } from 'vue'\n" +
      '\n' +
      "const name = ref('jack');\n" +
      '</script>\n' +
      '<style lang="scss">\n' +
      'input {\n' +
      '    color: #333;\n' +
      '}\n' +
      '</style>\n',
    template: {
      type: 'template',
      content: '\n    <input type="text" v-model="name">\n',
      loc: [Object],
      attrs: {},
      ast: [Object],
      map: [Object]
    },
    script: null,
    scriptSetup: {
      type: 'script',
      content: "\nimport { ref } from 'vue'\n\nconst name = ref('jack');\n",
      loc: [Object],
      attrs: [Object],
      lang: 'ts',
      setup: true
    },
    styles: [ [Object] ],
    customBlocks: [],
    cssVars: [],
    slotted: false,
    shouldForceReload: [Function: shouldForceReload]
  },
  errors: []
}

唯一的不同就是编译后的结果从原来的script上迁移到scriptSetup

compileTemplate

拿到之前parse后的结果后,需要对template进行进一步的转换,把template结果进一步编译成对应的js vnode函数

let compileredTemplate = compileTemplate({
    id: '123',
    filename: 'foo.vue',
    source: parsed.descriptor.template.content
})
console.log('parsed', compileredTemplate);

其中code的值就是最终模版编译的结果

{
  code: 'import { vModelText as _vModelText, withDirectives as _withDirectives, openBlock as _openBlock, createElementBlock as _createElementBlock } from "vue"\n' +
    '\n' +
    'export function render(_ctx, _cache) {\n' +
    '  return _withDirectives((_openBlock(), _createElementBlock("input", {\n' +
    '    type: "text",\n' +
    '    "onUpdate:modelValue": _cache[0] || (_cache[0] = $event => ((_ctx.name) = $event))\n' +
    '  }, null, 512 /* NEED_PATCH */)), [\n' +
    '    [_vModelText, _ctx.name]\n' +
    '  ])\n' +
    '}',
  ast: {
    type: 0,
    children: [ [Object] ],
    helpers: [
      Symbol(vModelText),
      Symbol(withDirectives),
      Symbol(openBlock),
      Symbol(createElementBlock)
    ],
    components: [],
    directives: [],
    hoists: [],
    imports: [],
    cached: 1,
    temps: 0,
    codegenNode: {
      type: 13,
      tag: '"input"',
      props: [Object],
      children: undefined,
      patchFlag: '512 /* NEED_PATCH */',
      dynamicProps: undefined,
      directives: [Object],
      isBlock: true,
      disableTracking: false,
      isComponent: false,
      loc: [Object]
    },
    loc: {
      start: [Object],
      end: [Object],
      source: '\n    <input type="text" v-model="name">\n'
    },
    filters: []
  },
  preamble: '',
  source: '\n    <input type="text" v-model="name">\n',
  errors: [],
  tips: [],
  map: {
    version: 3,
    sources: [ 'foo.vue' ],
    names: [ 'name' ],
    mappings: ';;;wCACI,oBAAkC;IAA3B,IAAI,EAAC,MAAM;IADtB,6DACgCA,SAAI;;kBAAJA,SAAI',
    sourcesContent: [ '\n    <input type="text" v-model="name">\n' ]
  }
}

我们把结果单独拿出来看下

import { vModelText as _vModelText, withDirectives as _withDirectives, openBlock as _openBlock, createElementBlock as _createElementBlock } from "vue"

export function render(_ctx, _cache) {
    return _withDirectives((_openBlock(), _createElementBlock("input", {
        type: "text",
        "onUpdate:modelValue": _cache[0] || (_cache[0] = $event => ((_ctx.name) = $event))
    }, null, 512 /* NEED_PATCH */)), [
        [_vModelText, _ctx.name]
    ])
}

最终返回了一个render函数,这里也就符合预期,vue组件中如果使用js的方式写,可以写一个render函数去渲染组件

compilerScript

根据parsed的结果来解析脚本部分,compileScript接收2个参数,第一个就是之前parse的结果, 然后再传入相应的option

let compileredScript = compileScript(parsed.descriptor, {
    id: '123'
})
console.log('parsed', compileredScript);

编译后的结果,content就是最终编译出的代码

{
  type: 'script',
  content: "import { defineComponent as _defineComponent } from 'vue'\n" +
    "import { ref } from 'vue'\n" +
    '\n' +
    '\n' +
    'export default /*#__PURE__*/_defineComponent({\n' +
    '  setup(__props, { expose }) {\n' +
    '  expose();\n' +
    '\n' +
    "const name = ref('jack');\n" +
    '\n' +
    'const __returned__ = { name }\n' +
    "Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true })\n" +
    'return __returned__\n' +
    '}\n' +
    '\n' +
    '})',
  loc: {
    source: "\nimport { ref } from 'vue'\n\nconst name = ref('jack');\n",
    start: { column: 25, line: 4, offset: 86 },
    end: { column: 1, line: 8, offset: 140 }
  },
  attrs: { lang: 'ts', setup: true },
  lang: 'ts',
  setup: true,
  bindings: { ref: 'setup-const', name: 'setup-ref' },
  imports: [Object: null prototype] {
    ref: {
      isType: false,
      imported: 'ref',
      source: 'vue',
      isFromSetup: true,
      isUsedInTemplate: false
    }
  },
  map: SourceMap {
    version: 3,
    file: null,
    sources: [ 'foo.vue' ],
    sourcesContent: [
      '<template>\n' +
        '    <input type="text" v-model="name">\n' +
        '</template>\n' +
        "<script lang='ts' setup>\n" +
        "import { ref } from 'vue'\n" +
        '\n' +
        "const name = ref('jack');\n" +
        '</script>\n' +
        '<style lang="scss">\n' +
        'input {\n' +
        '    color: #333;\n' +
        '}\n' +
        '</style>\n'
    ],
    names: [],
    mappings: ';AAIA,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AACzB;;;;;AAFwB;AAGxB,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;;;;;;;'
  },
  scriptAst: undefined,
  scriptSetupAst: [
    Node {
      type: 'ImportDeclaration',
      start: 1,
      end: 26,
      loc: [SourceLocation],
      importKind: 'value',
      specifiers: [Array],
      source: [Node]
    },
    Node {
      type: 'VariableDeclaration',
      start: 28,
      end: 53,
      loc: [SourceLocation],
      declarations: [Array],
      kind: 'const'
    }
  ]
}

content格式化之后的结果, 所以说setup只是语法糖,最终还是以defineComponent去包裹一个对象进行返回的形式

import { defineComponent as _defineComponent } from 'vue'
import { ref } from 'vue'


export default /*#__PURE__*/_defineComponent({
    setup(__props, { expose }) {
        expose();

        const name = ref('jack');

        const __returned__ = { name }
        Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true })
        return __returned__
    }

})

compileStyle

compileStyle 即解析SFC style模块的入口函数

由于sfc中style块是可以写多个的,所以parse最终的结果styles其实是个数组

由变量签名也可以看出

export interface SFCDescriptor {
  // ....
  styles: SFCStyleBlock[]
  
}

这里我们取第一个块打印出来看一下,实际情况下应该是去循环的

let compileredStyle = compileStyle({
    source: parsed.descriptor.styles[0].content,
    scoped: true,
    id: 'data-v-123'
})
console.log('parsed', compileredStyle);

编译结果

其中code即是最终的css结果

{
  code: '\ninput[data-v-123] {\n    color: #333;\n}\n',
  map: undefined,
  errors: [],
  rawResult: LazyResult {
    stringified: true,
    processed: true,
    result: Result {
      processor: [Processor],
      messages: [],
      root: [Root],
      opts: [Object],
      css: '\ninput[data-v-123] {\n    color: #333;\n}\n',
      map: undefined,
      lastPlugin: [Object]
    },
    helpers: {
      plugin: [Function: plugin],
      stringify: [Function],
      parse: [Function],
      fromJSON: [Function],
      list: [Object],
      comment: [Function (anonymous)],
      atRule: [Function (anonymous)],
      decl: [Function (anonymous)],
      rule: [Function (anonymous)],
      root: [Function (anonymous)],
      document: [Function (anonymous)],
      CssSyntaxError: [Function],
      Declaration: [Function],
      Container: [Function],
      Processor: [Function],
      Document: [Function],
      Comment: [Function],
      Warning: [Function],
      AtRule: [Function],
      Result: [Function],
      Input: [Function],
      Rule: [Function],
      Root: [Function],
      Node: [Function],
      default: [Function],
      result: [Result],
      postcss: [Function]
    },
    plugins: [ [Object], [Object], [Object] ],
    listeners: {
      Declaration: [Array],
      Rule: [Array],
      AtRule: [Array],
      OnceExit: [Array]
    },
    hasListener: true
  },
  dependencies: Set(0) {}
}

参考链接


vue3 -- @vue/compiler-sfc 单文件转换工具 -- 学习笔记

Android-Bitmap回收/复用机制

包括 recycle() 方法 bitmap 回收时机。

Android 系统版本的内存分配策略也有所不同,这是我们需要了解的:

系统版本 Bitmap 内存分配策略
Android 3.0 之前

Bitmap 对象存放在 Java Heap,而像素数据是存放在 native 内存中。

缺点:如果不手动调用 bitmap.recycle(),Bitmap native 内存的回收完全依赖 finalize() 回调,但是回调时机是不可控的

Android 3.0~7.0

Bitmap 对象和像素数据统一放到 Java Heap,即使不调用 bitmap.recycle(),Bitmap 像素也会随着对象一起被回收。

缺点:

1、Bitmap 全部放在 Java Heap,Bitmap 是内存消耗的大户,而 Max Heap 一般限制为 256、512MB,Bitmap 过大过多容易导致 OOM。

2、容易引起大量 GC,没有充分利用系统的可用内存

Android 8.0 及以后

1、使用了能够辅助回收 native 内存的 NativeAllocationRegistry 实现将像素数据放到 native 内存,并且可以和 Bitmap 对象一起快速释放,在 GC 的时候还可以考虑到这些 Bitmap 内存以防止被滥用。

2、新增硬件位图 Hardware Bitmap 解决图片内存占用过多和图像绘制效率过慢问题

手动调用recycle()

2.3 及以下版本,保存在 jvm + native 中,手动调用 recycle() 。

7.0 和 8.0 不需要调用 recycle(),下面是该版本下代码。

    /**
     * Free the native object associated with this bitmap, and clear the
     * reference to the pixel data. This will not free the pixel data synchronously;
     * it simply allows it to be garbage collected if there are no other references.
     * The bitmap is marked as "dead", meaning it will throw an exception if
     * getPixels() or setPixels() is called, and will draw nothing. This operation
     * cannot be reversed, so it should only be called if you are sure there are no
     * further uses for the bitmap. This is an advanced call, and normally need
     * not be called, since the normal GC process will free up this memory when
     * there are no more references to this bitmap.
     */
    //释放与此位图关联的本机对象,并清除对像素数据的引用。 这不会同步释放像素数据;
    //这是一个高级调用,通常不需要调用,因为当没有更多对此位图的引用时,正常的 GC 过程将释放此内存。
    public void recycle() {
        if (!mRecycled) {
            nativeRecycle(mNativePtr);
            mNinePatchChunk = null;
            mRecycled = true;
        }
    }
  
    private static native void nativeRecycle(long nativeBitmap);

7.0 跟 8.0 nativeRecycle 实现不同。

8.0 版本 Bitmap

static jboolean Bitmap_recycle(JNIEnv* env, jobject, jlong bitmapHandle) {
    LocalScopedBitmap bitmap(bitmapHandle);
    bitmap->freePixels();
    return JNI_TRUE;
}

void freePixels() {
    mInfo = mBitmap->info();
    mHasHardwareMipMap = mBitmap->hasHardwareMipMap();
    mAllocationSize = mBitmap->getAllocationByteCount();
    mRowBytes = mBitmap->rowBytes();
    mGenerationId = mBitmap->getGenerationID();
    mIsHardware = mBitmap->isHardware();
    //清空数据
    mBitmap.reset();
}

7.0 版本 Bitmap

static jboolean Bitmap_recycle(JNIEnv *env, jobject, jlong bitmapHandle) {
    LocalScopedBitmap bitmap(bitmapHandle);
    bitmap->freePixels();
    return JNI_TRUE;
}
//析构函数
Bitmap::~Bitmap() {
    doFreePixels();
}

void Bitmap::doFreePixels() {
    switch (mPixelStorageType) {
        //Invalid表示图片已经失效了,一般图片free掉之后就会是这种状态
        case PixelStorageType::Invalid:
            break;
        //外部存储
        case PixelStorageType::External:
            mPixelStorage.external.freeFunc(mPixelStorage.external.address,
                mPixelStorage.external.context);
            break;
        //匿名共享内存,Fresco 低版本内存优化,通过 BitmapFactory.Options.inPurgeable = true 
        //使得 bitmap 通过匿名共享内存方式保存
        case PixelStorageType::Ashmem:
            munmap(mPixelStorage.ashmem.address, mPixelStorage.ashmem.size);
            close(mPixelStorage.ashmem.fd);
            break;
        //java内存,主要看这种
        case PixelStorageType::Java:
            JNIEnv* env = jniEnv();
            LOG_ALWAYS_FATAL_IF(mPixelStorage.java.jstrongRef,
                "Deleting a bitmap wrapper while there are outstanding strong "
                "references! mPinnedRefCount = %d", mPinnedRefCount);
        //DeleteWeakGlobalRef 该函数删除一个弱全局引用,添加待删除的弱全局引用给 jvm
        env->DeleteWeakGlobalRef(mPixelStorage.java.jweakRef);
            break;
        }

        if (android::uirenderer::Caches::hasInstance()) {
            android::uirenderer::Caches::getInstance().textureCache.releaseTexture(
                mPixelRef->getStableID());
    }
}
  1. 8.0 中,手动调用 recycle() 方法,像素数据会立即释放;

  2. 7.0 版本中,调用 recycle() 方法像素数据不会立即释放,而是通过 DeleteWeakGlobalRef 交由 Jvm GC 处理。Java 层主动调用 recycle() 或者在 Bitmap 析构函数 freePixels() ,移除 Global 对象引用,这个对象是 Heap 内存一堆像素的空间。GC 时释放掉。二是 JNI 不再持有 Global Reference,并 native 函数执行后释放掉,但 Java 层的 Bitmap 对象还在,只是它的 mBuffer 和 mNativePtr 是无效地址,没有像素 Heap 的 Bitmap 也就几乎不消耗内存。Java 层 Bitmap 对象什么时候释放,生命周期结束自然会 free 掉。

回收机制

7.0 通过 java 层 BitmapFinalizer.finalize 实现,8.0 通过 native 层 NativeAllocationRegistry 实现。

7.0 及以下,保存在 jvm 虚拟机中,回收机制通过 BitmapFinalizer. finalize 实现。跟 BitmapFinalizer 而不跟 Bitmap 关联的原因是重写 finalize 方法的对象会被延迟回收,经过两次 gc 才会被回收。原因是重写 finalize 的对象在创建时会创建 FinalizerReference 并引用 Object,并将FR 关联到 ReferenceQueue 中,当第一次执行 gc 时候,会把 FR 放在 queue 中,其中有个守护线程持续读取 queue 中的数据,并执行 finalize 方法。

Bitmap(long nativeBitmap, byte[] buffer, int width, int height, int density,
            boolean isMutable, boolean requestPremultiplied,
            byte[] ninePatchChunk, NinePatchInsetStruct ninePatchInsets) {
        if (nativeBitmap == 0) {
            throw new RuntimeException("internal error: native bitmap is 0");
        }

        ...
        mNativePtr = nativeBitmap;
        // 这个对象对象来回收
        mFinalizer = new BitmapFinalizer(nativeBitmap);
        int nativeAllocationByteCount = (buffer == null ? getByteCount() : 0);
        mFinalizer.setNativeAllocationByteCount(nativeAllocationByteCount);
    }

    private static class BitmapFinalizer {
        private long mNativeBitmap;

        // Native memory allocated for the duration of the Bitmap,
        // if pixel data allocated into native memory, instead of java byte[]
        private int mNativeAllocationByteCount;

        BitmapFinalizer(long nativeBitmap) {
            mNativeBitmap = nativeBitmap;
        }

        public void setNativeAllocationByteCount(int nativeByteCount) {
            if (mNativeAllocationByteCount != 0) {
                //注销 native 内存
                VMRuntime.getRuntime().registerNativeFree(mNativeAllocationByteCount);
            }
            mNativeAllocationByteCount = nativeByteCount;
            if (mNativeAllocationByteCount != 0) {
                VMRuntime.getRuntime().registerNativeAllocation(mNativeAllocationByteCount);
            }
        }

        @Override
        public void finalize() {
            try {
                super.finalize();
            } catch (Throwable t) {
                // Ignore
            } finally {
                // finalize 这里是 GC 回收该对象时会调用
                setNativeAllocationByteCount(0);
                //本地析构函数,释放资源
                nativeDestructor(mNativeBitmap);
                mNativeBitmap = 0;
            }
        }
    }

    private static native void nativeDestructor(long nativeBitmap);

8.0 以上,保存在 jvm + native 中,NativeAllocationRegistry 中把 native 的文件描述符(句柄)跟 Cleaner 关联,Cleaner 其实是个虚应用,会在没有强应用关联的时候进行内存回收。

    // called from JNI
    Bitmap(long nativeBitmap, int width, int height, int density,
            boolean isMutable, boolean requestPremultiplied,
            byte[] ninePatchChunk, NinePatch.InsetStruct ninePatchInsets) {
        ...

        mNativePtr = nativeBitmap;
        long nativeSize = NATIVE_ALLOCATION_SIZE + getAllocationByteCount();
        //nativeGetNativeFinalizer() 方法传入 NativeAllocationRegistry
        NativeAllocationRegistry registry = new NativeAllocationRegistry(
                Bitmap.class.getClassLoader(), nativeGetNativeFinalizer(), nativeSize);
        //注册 Java 层对象引用与 native 层对象的地址
        registry.registerNativeAllocation(this, nativeBitmap);
    }

下面是 NativeAllocationRegistry.java 代码

public class NativeAllocationRegistry {

        private final ClassLoader classLoader;
        private final long freeFunction;
        private final long size;

        public NativeAllocationRegistry(ClassLoader classLoader, long freeFunction, long size) {
            ...
            //外部传入的 nativeGetNativeFinalizer ,有用
            this.freeFunction = freeFunction;
            this.size = size;
        }

        public Runnable registerNativeAllocation(Object referent, long nativePtr) {
            ...

            try {
                //注册 native 内存
                registerNativeAllocation(this.size);
            } catch (OutOfMemoryError oome) {
                applyFreeFunction(freeFunction, nativePtr);
                throw oome;
            }
            // Cleaner 绑定 Java 对象与回收函数
            Cleaner cleaner = Cleaner.create(referent, new CleanerThunk(nativePtr));
            return new CleanerRunner(cleaner);
        }


        private class CleanerThunk implements Runnable {
            private long nativePtr;

            public CleanerThunk(long nativePtr) {
                this.nativePtr = nativePtr;
            }

            public void run() {
                if (nativePtr != 0) {
                    //freeFunction 即为 nativeGetNativeFinalizer() 方法
                    applyFreeFunction(freeFunction, nativePtr);
                }
                registerNativeFree(size);
            }

        }

        private static class CleanerRunner implements Runnable {
            private final Cleaner cleaner;

            public CleanerRunner(Cleaner cleaner) {
                this.cleaner = cleaner;
            }

            public void run() {
                cleaner.clean();
            }
        }

        public static native void applyFreeFunction(long freeFunction, long nativePtr);
    }

NativeAllocationRegistry 内部是利用了 sun.misc.Cleaner.java 机制,简单来说:使用虚引用得知对象被GC的时机,在GC前执行额外的回收工作。

nativeGetNativeFinalizer()
// Bitmap.java
private static native long nativeGetNativeFinalizer();

// Bitmap.cpp
static jlong Bitmap_getNativeFinalizer(JNIEnv*, jobject) {
    // 转为long
    return static_cast<jlong>(reinterpret_cast<uintptr_t>(&Bitmap_destruct));
}

static void Bitmap_destruct(BitmapWrapper* bitmap) {
    delete bitmap;
}

nativeGetNativeFinalizer 是一个 native 函数,返回值是一个 long,这个值其实相当于 Bitmap_destruct() 函数的直接地址,Bitmap_destruct() 就是用来回收 native 层内存的。

故 NativeAllocationRegistry 利用虚引用感知 Java 对象被回收的时机,来回收 native 层内存;在 Android 8.0 (API 27) 之前,Android 通常使用Object#finalize() 调用时机来回收 native 层内存

Tips:Fresco 在 Android 4.4 及以下版本对 bitmap 内存做了优化,通过设置 BitmapFactory.Options.inPurgeable = true 使得 bitmap 保存在匿名共享内存中,减少了 Jvm 虚拟机内存占用。

继续阅读Android-Bitmap回收/复用机制

Spring Boot启动报错-"类文件具有错误的版本 61.0, 应为 52.0"

项目使用的 Spring Boot 升级到 3.0.5 版本

编译的时候报错如下:

Error:(5, 32) java: 无法访问org.springframework.lang.NonNull
  错误的类文件: /Users/xxxx/.m2/repository/org/springframework/spring-core/6.0.7/spring-core-6.0.7.jar(org/springframework/lang/NonNull.class)
    类文件具有错误的版本 61.0, 应为 52.0
    请删除该文件或确保该文件位于正确的类路径子目录中。

或者:

OpenJDK 64-Bit Server VM warning: Options -Xverify:none and -noverify were deprecated in JDK 13 and will likely be removed in a future release.
Connected to the target VM, address: '127.0.0.1:54101', transport: 'socket'
Exception in thread "main" java.lang.UnsupportedClassVersionError: org/springframework/boot/SpringApplication has been compiled by a more recent version of the Java Runtime (class file version 61.0), this version of the Java Runtime only recognizes class file versions up to 58.0
	at java.base/java.lang.ClassLoader.defineClass1(Native Method)
	at java.base/java.lang.ClassLoader.defineClass(ClassLoader.java:1017)
	at java.base/java.security.SecureClassLoader.defineClass(SecureClassLoader.java:151)
	at java.base/jdk.internal.loader.BuiltinClassLoader.defineClass(BuiltinClassLoader.java:821)
	at java.base/jdk.internal.loader.BuiltinClassLoader.findClassOnClassPathOrNull(BuiltinClassLoader.java:719)
	at java.base/jdk.internal.loader.BuiltinClassLoader.loadClassOrNull(BuiltinClassLoader.java:642)
	at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:600)
	at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
	at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522)
	at com.xxx.xxx.xxx.MainServiceApplication.main(MainServiceApplication.java:12)
Disconnected from the target VM, address: '127.0.0.1:54101', transport: 'socket'
原因

SpringBoot 使用了 3.0 或者 3.0 以上,因为 Spring 官方发布从 Spring 6 以及 SprinBoot 3.0 开始最低支持 JDK17,所以仅需将 SpringBoot 版本降低为 3.0 以下即可。

参考链接


.gitignore文件无法提交

问题

创建的 .gitignore 文件无法提交到 git 上

场景

log路径下创建了.gitignore文件, 文件内容:

*

想着忽略当前文件夹的所有内容. 此时想将 .gitignore文件提交上去, 运行git status 发现没有.gitignore文件的变动.

于是想着可能没反应过来, 就直接提交吧, 运行命令: git add .gitignore, 提示信息如下:

下列路径根据您的一个 .gitignore 文件而被忽略:
php/config/redis/log/.gitignore
提示:如果您确实要添加它们,使用 -f 参数。
提示:运行下面的命令来关闭本消息
提示:"git config advice.addIgnoredFile false"

解决

如此看来, 是我将这个文件忽略了, 运行命令检查是那里将其忽略了git check-ignore -v .gitignore. 输出结果:

php/config/redis/log/.gitignore:1:* .gitignore

表明, 是在.gitignore文件的第一行, 规则* 忽略了此文件.

吆西, 明白了, 解决方法也简单, 修改.gitignore文件内容, 将此文件排除即可, 修改后的内容:

* 
!.gitignore

此时就可以正常提交。

参考链接


.gitignore 文件无法提交

Android Cuttlefish模拟器(Android Cloud)

macOS Big Sur(11.7.5)编译Android 12.0源码过程总结

Android 11系统映像可直接将 ARM 指令转换成 x86 指令,因此以前很多需要真机测试的情况,现在只需要模拟器就可以进行操作了。

不过,根据官方博客 Run ARM apps on the Android Emulator 尾部的一段注意事项:

Note that the ARM to x86 translation technology enables the execution of intellectual property owned by Arm Limited. It will only be available on Google APIs and Play Store system images, and can only be used for application development and debug purposes on x86 desktop, laptop, customer on-premises servers, and customer-procured cloud-based environments. The technology should not be used in the provision of commercial hosted services.

这段事项说明,自己编译的镜像是没办法用上这个功能的,必须是Google编译好的镜像。

前置条件


  • macOS Big Sur(11.7.5)
  • Homebrew (1.1.9 或更高版本)
  • Xcode (13.2.1或更高版本)
  • Android Studio Electric Eel | 2022.1.1 Patch 2

注意:根据Google官方文档,2021年6月22日之后的Android系统版本不支持在macOS系统上构建,我们只能构建之前的版本,或者之后发布的以前版本的补丁修复。目前测试最高只能编译到Android 12.0,  Android  12.1编译不通过。

继续阅读macOS Big Sur(11.7.5)编译Android 12.0源码过程总结

macOS Big Sur(11.7.5)编译Android 11.0源码过程总结

Android 11系统映像可直接将 ARM 指令转换成 x86 指令,因此以前很多需要真机测试的情况,现在只需要模拟器就可以进行操作了。

不过,根据官方博客 Run ARM apps on the Android Emulator 尾部的一段注意事项:

Note that the ARM to x86 translation technology enables the execution of intellectual property owned by Arm Limited. It will only be available on Google APIs and Play Store system images, and can only be used for application development and debug purposes on x86 desktop, laptop, customer on-premises servers, and customer-procured cloud-based environments. The technology should not be used in the provision of commercial hosted services.

这段事项说明,自己编译的镜像是没办法用上这个功能的,必须是Google编译好的镜像。

前置条件


  • macOS Big Sur(11.7.5)
  • Homebrew (1.1.9 或更高版本)
  • Xcode (13.2.1或更高版本)
  • Android Studio Electric Eel | 2022.1.1 Patch 2

注意:根据Google官方文档,2021年6月22日之后的Android系统版本不支持在macOS系统上构建,我们只能构建之前的版本,或者之后发布的以前版本的补丁修复。目前测试最高只能编译到Android 12.0,  Android  12.1编译不通过。

继续阅读macOS Big Sur(11.7.5)编译Android 11.0源码过程总结