A method for reducing jar package volume and fast deployment
By employing a layered construction and multi-round verification approach, the problems of large Java project JAR file size and improper dependency management were solved, achieving JAR file size reduction and rapid deployment, while ensuring the accuracy and security of dependency loading.
Patent Information
- Authority / Receiving Office
- CN · China
- Patent Type
- Patents(China)
- Current Assignee / Owner
- ZHEJIANG FINGARD TECH CO LTD
- Filing Date
- 2025-12-08
- Publication Date
- 2026-04-21
AI Technical Summary
Traditional Java projects have large JAR files and repetitive dependencies, leading to high transmission costs and difficulties in version maintenance. Existing technical solutions suffer from JAR hell issues and lack accuracy in recovery when deployed in containers.
By minimizing business JAR packages during the slimmed-down JAR build and packaging phase, building global public dependency packages in layers, recording dependency metadata, and performing multiple rounds of verification and tokenization management during the recovery phase, the consistency and security of dependency loading order are ensured.
It achieves a 60%-80% reduction in JAR package size, a 90% increase in deployment speed, and the restored JAR package is 100% consistent with the original package in terms of structure and dependency order, eliminating the JAR hell problem and improving the reliability and security of deployment.
Smart Images

Figure CN121277543B_ABST
Abstract
Description
Technical Field
[0001] This invention belongs to the technical field of installation package deployment, and mainly relates to a method for reducing the size of Jar packages and deploying them quickly. Background Technology
[0002] In traditional Maven packaging, the main module JAR file of a Java project, along with external dependencies such as database drivers and logging frameworks, are merged into a single large JAR file. When a system contains multiple Java projects, duplicate external dependencies are packaged multiple times, leading to high transmission costs and difficulties in version maintenance. Existing technologies can result in single ROM packages reaching hundreds of MB or even GB in size, requiring technicians to transfer them to the customer's site via FTP, which is extremely time-consuming. Furthermore, each project's full JAR file iterates independently, and version upgrades of common dependencies require modifying project configurations individually, drastically increasing maintenance costs. To address this issue, some existing technologies offer dependency extraction and reuse solutions. For example, the prior art patent CN202210065108.3, entitled "Java Project Installation Package Deployment Method, Apparatus, Terminal Device, and Readable Medium," discloses a Java project installation package deployment method, apparatus, terminal device, and readable medium. The method includes: obtaining external dependency JAR packages, a list of external dependency JAR packages, and a service image of the main module from a compressed package uploaded during the service packaging stage; constructing a JAR package pool using the external dependency JAR packages; packaging the external dependency JAR package list, the service image, and the JAR package pool together to generate a ROM package; and performing the Java project installation package deployment operation based on the ROM package. This invention's Java project installation package deployment method effectively reduces the size of the installation package occupied by the Java project by deduplicating duplicate external dependency JAR packages during the packaging stage, and restores the external dependency JAR packages of the Java project during the deployment stage through restoration processing. This invention effectively reduces the installation package size before the Java project starts, thereby greatly improving the efficiency of loading the Java project.
[0003] This technical solution is suitable for enterprise private deployment of general Java projects, without the need for flexible adaptation to multiple components. However, this solution only supports Docker containerized deployment. While it can reduce size by deduplication, it sacrifices some recovery accuracy and introduces many application vulnerabilities. These vulnerabilities are known as "JAR hell." JAR hell is essentially a problem of uncontrolled Java dependency management. Specifically, when third-party JAR packages that a project depends on exhibit abnormalities such as duplicate packaging, version incompatibility, or disordered loading order, it can damage the integrity of the JAR package structure or class loading logic, ultimately leading to service failure to start, functional malfunctions, or even security vulnerabilities. These are typical pain points in traditional JAR package deployment scenarios. Furthermore, this technical solution requires additional adaptation if the build tool is switched later; although a common package is created, risks may still exist when multiple services depend on different versions of third-party packages. Summary of the Invention
[0004] In view of this, the present invention provides a method for reducing Jar package size and rapid deployment with a wider range of applications. While effectively reducing Jar package size, it improves the accuracy and security of recovery.
[0005] To address this issue, the present invention provides a method for reducing JAR package size and enabling rapid deployment, comprising a slimmed-down JAR build and packaging stage, a layered build and storage stage for global common dependency packages, and a dynamic business package recovery stage. In the slimmed-down JAR build and packaging stage, the generated business JAR package is minimized, and then a layered build of the global common dependency package is performed, retaining only business logic code and necessary dependency metadata. All third-party dependencies are uniformly stripped and aggregated into independent common dependency packages. The original JAR is traversed, only non-stripped dependencies are written, and the full dependency order list and the list of dependencies not actually written are synchronously recorded and stored. In the dynamic business package recovery stage... During the recovery phase, the first step is to prepare public dependencies. Users download the selected public dependency compressed packages to a local temporary directory, where an automated tool decompresses them to a unified dependency cache path. This directory centrally stores all third-party JAR files that may be shared by multiple business systems, avoiding duplicate transmission and redundant storage. Once recovery is confirmed, the tool reads the dependency metadata, extracts the name and expected size of each ignored dependency, and compares it one by one with the actual files in the locally decompressed public dependency directory. Only when the file exists and the size is exactly the same is it considered a match; otherwise, the recovery is interrupted and an alarm is triggered, effectively preventing dependencies from being tampered with or having version mismatches.
[0006] Preferably, security pre-processing is performed before the build and packaging stage of the slimmed-down JAR, by reporting the list of third-party dependencies that are not actually written to the JAR to the company's internal remote server, ensuring that this data is only stored in an internal controlled environment and is not leaked with the release package.
[0007] Preferably, during the build and packaging phase of the slimmed-down JAR, the regular command `mvn clean package` is executed to generate the original JAR package containing all dependencies. After the original JAR package is generated, a custom plugin is triggered. Through the Maven plugin, based on the metadata reported during the packaging phase, the remote server creates a reusable public dependency package according to the active time dimension. For the deployment of each business system, the recovery tool processes the uploaded slimmed-down JAR packages one by one. Before processing, the file type is first verified, and subsequent operations are only performed on standard JAR formats.
[0008] Preferably, after the slimming operation is completed, the plugin serializes two key metadata structures into JSON format and embeds them in the META-INF directory of the slimmed-down package. The thin-dependency.json file stores dependency information that was not actually written, including dependency name, version, and expected file size; the thin-dependency-sequence.json file records the injection order of all dependencies, ensuring dependency topology consistency during recovery. This metadata becomes the core guiding principle for on-site recovery.
[0009] Preferably, during the distribution preparation phase, the backend service aggregates all historically ignored dependencies based on reported data, calculates activity levels by time, and filters out frequently ignored third-party dependency packages from the last three, six, and twelve months. These dependencies are packaged into three public dependency compressed packages of different granularities and uploaded to a designated directory on the enterprise FTP server; each compressed package is digitally signed to ensure content integrity. Users select the corresponding version of the public dependency package based on their last upgrade time, achieving minimal download on demand.
[0010] Preferably, when verifying the file type before processing, it is necessary to check whether the thin-dependency.json file exists in the META-INF directory. If it does not exist, it is considered that the recovery has been completed or that it is not the target package, and the processing is skipped.
[0011] Preferably, whenever a dependency to be processed is found to be at the head of the list that has not yet been written to, the corresponding file is retrieved from the local cache directory and written to a new package. Simultaneously, the entry is removed from both lists to ensure that the dependency injection order is consistent with the original build. Furthermore, when processing dependencies already included in the slimmed-down package, their names are strictly verified to match the next entry in the order list; if they do not match, the process is terminated immediately. This prevents security issues such as SPI hijacking or bean overriding caused by malicious adjustments to the dependency loading order.
[0012] Preferably, multiple rounds of boundary check logic are set throughout the recovery loop, including fallback checks in the middle and at the end of the loop, to handle boundary anomalies such as concurrent modifications and missing files. After recovery, the system forcibly verifies whether both metadata lists have been cleared. Only when the full dependency order list is empty and the list of dependencies not actually written is empty can it be considered that all dependencies have been correctly injected without omission or redundancy.
[0013] Preferably, a recovery completion marker is written into the newly generated complete Jar package. The location of this marker is encrypted and cannot be modified in reverse. It serves as proof that the package has passed a complete security verification. After that, the package can be started normally, and the operation and maintenance system can quickly identify the trusted status of the package by checking this marker.
[0014] Preferably, if an interruption occurs during the recovery process and the system restarts, the tool first checks whether a recovery completion marker already exists in the Jar package. If the marker has been written, the package is determined to have completed a safe recovery, and the process is terminated.
[0015] By adopting this technical solution, this invention achieves a deep balance and comprehensive optimization of JAR package slimming efficiency, deployment reliability, and scenario adaptability in microservice scenarios. Its core goal is to eliminate JAR hell by building a full-chain solution through layered construction, metadata management, and multi-round verification. Compared with existing technologies, it first achieves a balance between slimming and accurate recovery. By recording the dependency loading priority through a full list of third-party dependencies and using dual metadata files, it ensures that the recovered JAR package is 100% consistent with the original package in terms of structure and dependency order, thus avoiding service startup failures caused by abnormal dependency loading order. At the same time, it specifically addresses the problem of uncontrollable dependency loading order. During recovery, it strictly injects dependencies according to the order recorded in thin-dependency-sequence.json to ensure 100% consistency with the original JAR package loading order. It also compares thin-dependency.json with local public dependencies one by one and sets up list empty checks to prevent dependency tampering or omissions, thereby solving the problem of missing checks.
[0016] Secondly, compared with existing technologies, the reliability assurance mechanism of this invention is more comprehensive. It not only verifies the local dependency matching through dependency metadata, but also designs multiple fallback operations through duplicate dependency matching and list empty verification. It has been verified in a production environment to achieve zero-accident deployment, significantly reducing the risk of on-site operation and maintenance for customers. Moreover, the technical solution described in this invention has extremely strong scenario adaptability. It can run without relying on a containerized environment, perfectly adapting to the deployment requirements of non-containerized microservices. It can also accurately extract pure technical fixed dependencies to adapt to the customized needs of customers with multiple databases and multiple message queues. At the same time, it generates multiple versions of global common dependency packages according to active dependencies at different time stages to meet the implementation scenarios of different upgrade cycles. In the layered construction, third-party dependencies are separated from business JARs and uniformly collected into a global common dependency package. Multiple business systems share the same common dependency, which further avoids duplicate packaging and transmission, and specifically solves the problem of duplicate dependencies.
[0017] Finally, this invention also has good scalability, supports metadata reporting to remote servers to achieve dynamic management of public dependencies, and can be further extended to include security mechanisms for encryption compression and dynamic decryption loading of self-developed packages, further strengthening the security of component transmission and storage, and is more in line with the complex needs of enterprise-level microservice private deployment. Attached Figure Description
[0018] Figure 1 This is a flowchart illustrating the compression process in a method for reducing JAR package size and enabling rapid deployment according to the present invention.
[0019] Figure 2 This is a flowchart illustrating the recovery process in a method for reducing JAR package size and enabling rapid deployment according to the present invention.
[0020] Figure 3 This is a schematic diagram showing the comparison of data packet size before and after using the method for reducing Jar packet size and rapid deployment in an embodiment of the present invention. Detailed Implementation
[0021] To make the objectives, technical solutions, and advantages of the embodiments of the present invention clearer, the technical solutions of the embodiments of the present invention will be clearly and completely described below with reference to the accompanying drawings. Obviously, the described embodiments are only some embodiments of the present invention, and not all embodiments. Based on the embodiments of the present invention, all other embodiments obtained by those skilled in the art without creative effort are within the scope of protection of the present invention.
[0022] The terms "first," "second," "third," "fourth," etc. (if present) in the specification, claims, and accompanying drawings of this invention are used to distinguish similar objects and are not necessarily used to describe a specific order or sequence. It should be understood that such data can be interchanged where appropriate so that embodiments of the invention described herein can be implemented in orders other than those illustrated or described herein.
[0023] It should be understood that in the various embodiments of the present invention, the sequence number of each process does not imply the order of execution. The execution order of each process should be determined by its function and internal logic, and should not constitute any limitation on the implementation process of the embodiments of the present invention.
[0024] It should be understood that in this invention, "comprising" and "having," and any variations thereof, are intended to cover non-exclusive inclusion, for example, a process, method, system, product, or device that includes a series of steps or units is not necessarily limited to those steps or units that are explicitly listed, but may include other steps or units that are not explicitly listed or that are inherent to such process, method, product, or device.
[0025] It should be understood that in this invention, "multiple" refers to two or more. "And / or" is merely a description of the relationship between related objects, indicating that three relationships can exist. For example, "and / or B" can represent: A existing alone, A and B existing simultaneously, and B existing alone. The character " / " generally indicates that the preceding and following related objects are in an "or" relationship. "Contains A, B, and C", "Contains A, B, and C" means that all three A, B, and C are contained; "Contains A, B, or C" means that one of A, B, and C is contained; "Contains A, B, and / or C" means that any one, two, or three of A, B, and C are contained.
[0026] It should be understood that in this invention, "B corresponding to A", "B corresponding to A", "A and B correspond", or "B and A correspond" means that B is associated with A, and B can be determined based on A. Determining B based on A does not mean determining B solely based on A; B can also be determined based on A and / or other information. Matching A and B means that the consistency between A and B is greater than or equal to a preset threshold.
[0027] Depending on the context, "if" as used here can be interpreted as "when," "when," "in response to determination," or "in response to detection."
[0028] The technical solution of the present invention will be described in detail below with reference to specific embodiments. These specific embodiments can be combined with each other, and the same or similar concepts or processes may not be described again in some embodiments.
[0029] This invention is illustrated through examples. When deploying Java applications at customer sites, enterprises face the problem of excessively large JAR file sizes and security risks associated with third-party dependencies. To address this, the enterprise designed and implemented a secure and controllable JAR file reduction and on-site recovery solution, which effectively ensures the integrity of dependencies and the trustworthiness of package files during the deployment process, thereby preventing JAR corruption.
[0030] This invention relates to the use and creation of corresponding dependency packages, which are pre-written, reusable code libraries or modules that are referenced and used by currently developing software projects to achieve specific functions without requiring developers to write all the code from scratch.
[0031] like Figure 1As shown, during the packaging phase, users minimize the original JAR file, separating business logic code from third-party dependencies. Only business logic and dependency metadata are retained during packaging to generate a slimmed-down JAR file. Simultaneously, the list of third-party dependencies not actually written into the JAR file is uploaded to a remote internal server for centralized management. This operation ensures that the dependency list is not leaked and public dependencies are not directly exposed in the release package, thereby reducing the attack surface and mitigating security risks caused by third-party library vulnerabilities. All third-party dependencies are uniformly collected and compressed into a public dependency package, stored in a designated directory on a controlled internal FTP server, and only authorized on-site users can actively download it according to deployment needs. This method achieves centralized control of dependency resources, eliminating the possibility of dependency packages being tampered with or replaced during transmission, and ensuring the reliability of dependency sources. During the on-site recovery phase, the system first checks whether the target JAR file already contains a recovery completion marker. If it already exists, subsequent operations are skipped to prevent repeated recovery from causing package structure corruption or malicious injection. After the recovery process starts, the system reads the dependency metadata embedded in the slimmed-down JAR file and compares it one by one with the locally downloaded and decompressed public dependency files. When reading dependency metadata, both the dependency name and file size must be obtained simultaneously. Only dependencies with identical names and sizes are allowed to be injected, ensuring that dependencies without version errors or malicious tampering are included in the final package. Next, the system verifies that the currently injected dependency matches the next expected dependency in the built-in full dependency order list. Any deviation in order will immediately interrupt the recovery process, preventing security vulnerabilities or operational anomalies caused by malicious adjustments to dependency loading order. After all dependencies are injected, the system forcibly verifies that two key lists are empty: the full dependency order list and the list of dependencies not yet written. Only when both are empty is it considered that all dependencies have been correctly processed, without omissions or redundancy, ensuring that no security-critical libraries are missing and no unnecessary dependencies have been introduced. Finally, after all verification steps pass, the system writes a recovery completion marker to the Jar package. This marker serves as the sole proof that the Jar package has completed security recovery and is a prerequisite for subsequent startup, preventing insecure packages that have not been fully verified from being mistakenly used. This solution constructs a full-link security control system from packaging to on-site recovery by combining dependency minimization, internal storage, multi-level verification, and tokenized management. It focuses on ensuring the integrity and trustworthiness of JAR packages during the customer's on-site recovery process, effectively addressing the basic security requirements of software packages in the deployment environment, and achieving systematic protection against dependency risks without relying on strong encryption or permission mechanisms.
[0032] This process actually uses two plugins. The first plugin removes unnecessary third-party JAR files during packaging based on filtering rules, while retaining some contextual information. The second plugin supplements the third-party JAR files based on the contextual information to obtain a complete and executable JAR file.
[0033] like Figure 1 As shown, in specific operations, during the packaging stage, the standard packaging command is: Execute command
[0034] mvn clean package
[0035] After the clean package lifecycle is completed, the self-developed Maven plugin One Click DeployThin Jar Mojo is triggered. This plugin completes the build of the slimmed-down Jar and the preprocessing of the self-developed components according to the following process: Dependency filtering and preprocessing of self-developed components obtain the full build-time dependency list through plugin annotation configuration and combine it with the runtime dependency list. Annotation definition:
[0036] Plugin core configuration annotations
[0037] @Mojo(name = "oneClickDeployThin", defaultPhase =LifecyclePhase.PACKAGE, requiresDependencyCollection =ResolutionScope.COMPILE_PLUS_RUNTIME)
[0038] public class OneClickDeployThinJarMojo extends AbstractMojo {
[0039] Based on a pre-defined list of filterable third-party dependencies, static dependencies that need to be removed are selected. At the same time, a dedicated preprocessing process is performed on the self-developed general technology component package, my-safe.jar, which is not included in the removal scope.
[0040] Then, the self-developed general-purpose technology component package my-safe.jar is preprocessed with encryption. The original byte stream of my-safe.jar is read, and combined with the exclusive key issued by the enterprise-level KMS, the AES-256-GCM algorithm is used to perform encryption and compression, generating my.safe.zip. my.safe.zip is renamed to my-safe.jar to ensure consistency with the naming format of regular dependency packages and to adapt to the subsequent logic of writing slimmer JAR dependencies. The encryption algorithm, key index, and SHA-256 hash value of the original file are recorded to form the encrypted component metadata for subsequent decryption and verification.
[0041] The full JAR file generated by `mvn clean package` is traversed and restructured using a byte stream to produce a slimmed-down JAR. The core processing logic is as follows: A full dependency order list is constructed, recording the loading priority of all dependencies. Dependencies that can be stripped are skipped from the list; regular dependencies are directly written to the slimmed-down JAR. Dedicated handling for self-developed encryption components: The preprocessed `my-safe.jar` is forcibly written to the `BOOT-INF / lib` directory of the slimmed-down JAR, and the `"componentType":"self-developed-encrypted"` identifier is added to the full dependency order list to provide identification criteria for subsequent decryption and loading.
[0042] To ensure the accuracy and safety of on-site recovery for clients, three types of structured metadata are injected into the META-INF directory of the slimmed-down Jar. All three types of structured metadata are serialized in JSON format.
[0043] Thin-dependency.json: Records the metadata of third-party dependencies stripped during the packaging stage, including name, version, file size, and SHA-256 hash.
[0044] Full dependency sequence list (thin-dependency-sequence.json): Records the dependency loading order of the original JAR files, including exclusive identifiers for self-developed encrypted components.
[0045] Metadata of the self-developed encryption component (my-safe-meta.json): Records the encryption configuration and integrity verification information of my-safe.jar, as shown in the example below:
[0046] json
[0047] {
[0048] "componentName":"my-safe.jar",
[0049] "componentVersion":"1.0.0",
[0050] "encryptAlgorithm":"AES-256-GCM",
[0051] "encryptMode":"Compress-Then-Encrypt",
[0052] "keyIndex":"KMS-MYSAFE-202409", / / Associated enterprise KMS key index
[0053] "originalFileHash":"a87ff679a2f3e71d9181a67b7542122c", / / SHA-256 hash
[0054] "integrityCheckType":"Hash+GCM-Tag",
[0055] "componentType":"self-developed-encrypted"
[0056] }
[0057] Metadata writing code snippet:
[0058] Core code implementation
[0059] thinJarOutput.putNextEntry(new ZipEntry("META-INF / thin-dependency.json"));
[0060] String excludeMeta = JsonUtils.serialize(excludeDependencyList);
[0061] thinJarOutput.write(excludeMeta.getBytes(StandardCharsets.UTF_8));
[0062] thinJarOutput.closeEntry();
[0063] thinJarOutput.putNextEntry(new ZipEntry("META-INF / thin-dependency-sequence.json"));
[0064] String sequenceMeta = JsonUtils.serialize(fullDependencySequence);
[0065] thinJarOutput.write(sequenceMeta.getBytes(StandardCharsets.UTF_8));
[0066] thinJarOutput.closeEntry();
[0067] / / Inject metadata of self-developed encryption components
[0068] thinJarOutput.putNextEntry(newZipEntry("META-INF / my-safe-meta.json"));
[0069] String safeComponentMeta=JsonUtils.serialize
[0070] (mySafeComponentMeta);
[0071] thinJarOutput.write(safeComponentMeta.getBytes(StandardCharsets.UTF_8));
[0072] thinJarOutput.closeEntry();
[0073] Metadata of self-developed encrypted components extracted from the dependency list is reported to the enterprise-level dependency management platform via HTTPS protocol. The platform performs deduplication and version aggregation on the dependency data based on time windows to generate a "global active dependency dataset", providing data support for the subsequent construction of public dependency packages.
[0074] Regular third-party dependency packages: aggregated and deduplicated by the dimension of "active in the last N months", and packaged into 3 versions of Global-Common-Deps-V{X}.zip using the LZ4 high compression algorithm;
[0075] Self-developed encrypted component package: MySafe-Component-V{Y}.zip is built separately according to version. The package contains the encrypted my-safe.jar and the corresponding metadata index file, which is associated with the my-safe-meta.json in the slimmed-down Jar. All compressed packages generate integrity verification values through SHA-512 and are stored in an encrypted storage partition of an enterprise-level FTP service, allowing users to download on demand.
[0076] like Figure 3 The image shows a volume comparison after the compression package of this invention has been reduced in size.
[0077] like Figure 2 As shown, the on-site recovery is based on a model of deploying a common dependency once and restoring multiple business packages, and the entire process is automated through self-developed recovery tools.
[0078] Users download the target versions of Global-Common-Deps-V{X}.zip and MySafe-Component-V{Y}.zip from the FTP server. The recovery tool automatically verifies the SHA-512 value of the compressed files to ensure that they have not been tampered with during transmission. The tool unzips the regular dependencies to the Local-Deps-Repo directory, unzips the self-developed encryption component to the Local-Encrypted-Repo subdirectory, and reads the metadata index file and pre-matches it with the my-safe-meta.json file in the slimmed-down JAR file to verify the version and confirm the consistency of the encryption algorithm. Regardless of the number of business packages to be recovered, this step only needs to be performed once, achieving global reuse of common dependencies.
[0079] After receiving the slimmed-down JAR file, the recovery tool triggers a multi-stage verification-recovery process. The core logic is as follows:
[0080] File type filtering: If the input file is not in Jar format, processing is terminated directly, and the result feedback stage is entered; Metadata existence verification: Check if META-INF / thin-dependency.json exists. If it does not exist, it is determined to be a full Jar and no processing is required; Recovery status verification: Check META-INF / Recovery-Completed.tag, the recovery completion marker. If it exists, skip the duplicate processing. Dependency matching verification: Parse thin-dependency.json and compare the name, version, and file size of the dependencies in Local-Deps-Repo one by one. If the match fails, an exception alarm is triggered; Read thin-dependency-sequence.json and my-safe-meta.json to initialize the dependency recovery queue and the encryption component decryption context. Traverse the thinned Jar byte stream and reconstruct the full Jar according to the following rules:
[0081] Non-JAR type resources: written directly to the target JAR, maintaining the original directory structure;
[0082] Regular Jar dependency: compare the dependency to restore the first element of the queue; if a match is found, write it to the target Jar and remove the element from the queue; otherwise, trigger an exception.
[0083] Self-developed encryption component my-safe.jar:
[0084] Read the encrypted my-safe.jar from Local-Encrypted-Repo;
[0085] The corresponding key is obtained from the enterprise KMS based on the keyIndex in my-safe-meta.json;
[0086] Decrypt using the AES-256-GCM algorithm to generate the original Jar byte stream, and verify that the SHA-256 hash matches the metadata.
[0087] Write the original byte stream to the BOOT-INF / lib directory of the target Jar and remove the corresponding element from the dependency recovery queue; repeat the dependency recovery queue matching-writing logic to handle dependency remnants in critical scenarios; confirm that both the dependency recovery queue and the encryption component processing queue are empty, otherwise trigger an exception, thus completing the integrity verification.
[0088] Recovery tagging and class loading logic injection: Write Recovery-Completed.tag to the META-INF directory of the target Jar, and inject a custom ClassLoader configuration into META-INF / spring.factories:
[0089] properties
[0090] #Inject custom class loading logic for self-developed encryption components and bind the decryption-loading lifecycle.
[0091] org.springframework.boot.loader.Launcher=com.enterprise.loader.MySafeEncryptedClassLoader
[0092] If any step fails, a structured exception log is output, containing error codes, dependency identifiers, and verification failure items, supporting rapid problem location. After recovery, the target JAR file has the full capability to load runtime dependencies and encrypted components, and the service can be started directly.
[0093] First, the entire file package needs to undergo dependency integrity and legality verification to prevent malicious or abnormal dependencies from being mixed in. To this end, this invention employs multi-step strong verification during the on-site recovery phase to ensure that the recovered Jar package dependencies have not been tampered with or replaced; this is a core security feature.
[0094] During dependency metadata two-way verification and recovery, the dependency metadata in "META-INF / thin-dependency.json" of the slimmed-down JAR file needs to be extracted and compared one by one with the locally unzipped public dependency packages. Recovery only continues if the names match and the file sizes are exactly the same. If they do not match, the process jumps directly to error handling to prevent malicious dependencies, such as tampered third-party JARs or incorrect dependencies, such as incompatible JARs mixed into the full JAR package. During the recovery process, it is necessary to verify whether the current dependency name in the slimmed-down JAR matches the first member of the full dependency sequence list (thin-dependency-sequence.json). If they do not match, the recovery is interrupted to prevent runtime abnormalities or security vulnerabilities caused by tampering with the dependency loading order.
[0095] After the recovery is complete, a mandatory check is performed to verify that the full dependency order list and the actual unwritten dependency list are both empty, ensuring that all dependencies have been processed normally and that there are no omissions or redundant dependencies, thus avoiding security risks caused by missing or redundant dependencies.
[0096] During the internal data reporting and storage packaging phase, the list of third-party dependencies that are not actually written into the data is reported to the company's internal remote server, rather than being publicly stored. The public dependency compressed package is only placed in a designated location on the company's FTP server, and users need to download it as needed. The entire process relies on internal controlled channels to avoid the dependency list and public dependency package being obtained by unauthorized personnel, thereby reducing the risk of dependency packages being tampered with and the list being used for targeted attacks.
[0097] The recovery process is designed to prevent duplication and tampering through tokenization control. During on-site recovery, the system checks whether the Jar package has a recovery completion marker. If it already exists, it will not be processed again to avoid damage to the Jar package structure or malicious dependency injection due to repeated recovery. At the same time, the completion marker is only written after the entire recovery process has been verified. It serves as proof that the Jar package has been safely recovered, preventing incomplete Jar packages that have not completed verification from being misused.
[0098] The technical solution described in this invention achieves excellent file size reduction. For a single application, the reduced-size business package itself can achieve a 60%-80% reduction in size. This means that a package that was originally 500MB may only be around 100MB after reduction. This not only reduces storage space but also makes the download speed 90% faster than a single complete package. When deploying multiple service instances or microservice clusters, because common dependency packages only need to be downloaded once, all subsequent service updates only require downloading the additional reduced-size package, thereby reducing the overall download time by more than 90%. Furthermore, the reduction in file size is only the surface-level benefit; the deeper value of this solution lies in ensuring, through metadata (thin-dependency.json, thin-dependency-sequence.json), that the restored package is 100% consistent with the original package in terms of structure and dependency order, solving the "JAR hell" problem, which is something that existing technical solutions cannot achieve.
[0099] This invention is compared with the technical solution described in the prior art invention patent CN202210065108.3, entitled "Java Project Installation Package Deployment Method, Device, Terminal Equipment and Readable Medium". The technical solution used in this invention is actually: Spring Boot Thin JAR / Externalized Dependencies, and its core technology includes:
[0100] 1. Do not include dependencies in the JAR file during packaging;
[0101] 2. Specify the dependency location using -Dloader.path=xxx at startup;
[0102] 3. The main package is smaller, improving build and deployment efficiency.
[0103] This is indeed one of the best practices in large-scale projects and microservice architectures in existing technologies. However, Spring Boot traverses the JAR packages in the loader.path directory in file system order, loads them using LaunchedURLClassLoader, and builds the classpath in chronological order. This order is usually lexicographical in the filenames, but it is not guaranteed to be absolutely consistent because the directory traversal order may differ across operating systems and file systems. Once a class is found in a JAR, the search stops, and subsequent JARs are not traversed. Moreover, because it is a sequential search, classes in earlier JAR packages will override classes with the same name in later JARs. This is similar to the sequential dependencies in classpath -cp a.jar:b.jar, and errors cannot be recovered immediately.
[0104] In summary, the existing method of automatically loading all JAR packages in a directory using `-loader.path` cannot guarantee 100% consistency in loading order without additional control. When implementing the technology, any method that cannot guarantee 100% accuracy is meaningless.
[0105] This invention aims to build a highly reliable system by proactively controlling dependencies. It achieves 100% precise control over dependencies by actively recording and embedding two metadata files, thin-dependency.json and thin-dependency-sequence.json, during the packaging stage. thin-dependency.json ensures strict verification of the names, versions, and sizes of local public dependencies during recovery, preventing tampering or mismatches. thin-dependency-sequence.json precisely records the loading order of all dependencies in the original JAR file, allowing the recovery tool to inject dependencies one by one strictly according to the original build topology order. This completely avoids the inconsistent class loading order problem caused by the uncontrollable dependency file system traversal order in the traditional -Dloader.path method. It is important to note that both metadata files are indispensable. Combined with recovery completion markers, multi-round boundary checks, and internalized dependency management, proactive, precise, and verifiable control is achieved throughout the entire chain from packaging to deployment, thus truly achieving 100% accuracy and security in dependency recovery.
Claims
1. A method for reducing jar package size and fast deployment, the method comprising: This includes the slimmed-down Jar build and packaging stage, the global public dependency package layered build and storage stage, and the business package dynamic recovery stage. In the slimmed-down Jar build and packaging stage, the generated business Jar package is minimized, and then the global public dependency package is layered, retaining only the business logic code and necessary dependency metadata. All third-party dependencies are uniformly stripped and aggregated into an independent public dependency package. Traverse the original JAR, write only non-stripped dependencies, and synchronously record and store the full dependency order list and the actual unwritten dependency list; during the dynamic recovery phase of the business package, first execute the public dependency preparation step, where the user downloads the selected public dependency compressed package to the local temporary directory, and the automated tool decompresses it to the unified dependency cache path; After confirming the need for recovery, the tool reads dependency metadata, extracts the name and expected size of each ignored dependency, and compares it one by one with the actual files in the locally unzipped public dependency directory. Whenever a dependency to be processed is found at the head of the list of dependencies not actually written, the corresponding file is retrieved from the local cache directory and written to the target Jar. Simultaneously, the entry corresponding to the current dependency to be processed is removed from both the full dependency order list and the list of dependencies not actually written, ensuring that the dependency injection order is consistent with the original build. At the same time, when processing dependencies already included in the slimmed-down package, its name is strictly verified to match the entry corresponding to the next un-stripped dependency in the full dependency order list. If they do not match, the process is terminated immediately. Specifically, after receiving the slimmed-down Jar, the recovery tool triggers a multi-stage verification-recovery process. The core logic is as follows: read the full dependency order list and initialize the dependency recovery queue; traverse the slimmed-down Jar byte stream and reconstruct the full Jar according to the following rules: non-Jar type resources: directly written to the target Jar, maintaining the original directory structure; regular Jar dependencies: compared with the first element of the dependency recovery queue, and if they match, written to the target Jar. Remove queue elements; if a mismatch occurs, trigger an exception. Write the original byte stream to the target Jar's BOOT-INF / lib directory and remove the corresponding element from the dependency recovery queue. Repeat the dependency recovery queue matching-writing logic to handle dependency remnants in critical scenarios. Once all dependencies are injected, confirm that both the full dependency order list and the actual unwritten dependency list are empty; otherwise, trigger an exception. This completes the integrity check.
2. The method for reducing the volume of a Jar package and rapid deployment of claim 1, wherein, Before the build and packaging phase of the slimmed-down JAR file, a security pre-processing is performed, and the list of third-party dependencies that are not actually written is reported to the company's internal remote server.
3. The method for reducing the volume of a Jar package and rapid deployment of claim 1, wherein, After the slimming operation is completed, the plugin serializes the full dependency sequence list and the list of dependencies that were not actually written into JSON format and embeds them in the META-INF directory of the slimmed package. The thin-dependency.json file stores the dependency information that was not actually written, including the dependency name, version and expected file size. The thin-dependency-sequence.json file records the injection order of the full dependencies to ensure the consistency of the dependency topology during recovery.
4. The method for reducing the size of a jar and rapid deployment of claim 1, wherein, During the distribution preparation phase, the backend service aggregates all historically ignored dependencies based on the reported data, calculates activity levels by time dimension, and filters out third-party dependency packages that have been frequently ignored in the last three months, six months, and twelve months. These dependencies are packaged into three public dependency compressed packages of different granularities and uploaded to the designated directory on the enterprise FTP server. Each compressed package is protected by a digital signature to ensure the integrity of the content.
5. The method for reducing the size of a jar and rapid deployment as claimed in claim 1, wherein, Before restoring, when verifying the file type, it is necessary to check whether the thin-dependency.json file exists in the META-INF directory. If it does not exist, it is considered that the restoration has been completed or that it is not the target package, and the process is skipped.
6. The method for reducing the size of a jar and rapid deployment of claim 1, wherein, A recovery completion marker is written into the newly generated complete JAR file. The location of this marker is encrypted and cannot be modified in reverse. It serves as proof that the file has passed a complete security verification. After that, the file can be started normally, and the operation and maintenance system can quickly identify the trusted status of the file by checking this marker.
7. The method for reducing the volume of a Jar package and rapid deployment of claim 6, wherein, If an interruption occurs during the recovery process and the system restarts, the tool first checks whether a recovery completion marker already exists in the Jar package. If the marker has been written, the package is determined to have completed a safe recovery, and the process is terminated.
Citation Information
Patent Citations
Java project installation package deployment method and device, terminal equipment and readable medium
CN114489699A