SpringBoot 打成jar包供第三方引用自动装配方案实现

本文详细介绍如何将SpringBoot项目打成jar包,供第三方作为组件引用,包括手动配置、注解引入、SPI机制等自动装配方案。通过具体示例,如使用Jedis连接Redis,演示不同配置方式下的组件注册过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

SpringBoot 打成jar包供第三方引用自动装配方案实现

每天多学一点点~
话不多说,这就开始吧…

1.前言

看了源码之后,总有种蠢蠢欲动的感觉,想着以后啥时候牛逼了,自己也可以用springboot写个第三方组件,让别人引入jar包就行。虽然知道目前水平有限,先试试普通的jar包如何与spring自动装配吧~
环境 jdk1.8 springboot 2.1.12.RELEASE

2.使用者手动配置 basePackages

这种个人觉比较low,不友好,使用者需要在类上加@ComponentScan,而对于开发者很简单,
不需要对项目进行任何其余配置。

@Configuration
@ComponentScan(basePackages = {"com.zjq.jartest.**"})
public class TestConfig{

}

配置方式: 在SpringBoot启动类或能被Spring发现的 Configuration 类上增加 @ComponentScan(basePackages = {“com.zjq.jartest.**”})

通过此方式配置后,Spring会在启动时扫描 com.zjq.jartest 这个包,我们的组件自然而然也会被注册为Spring Bean

3.使用者通过注解方式引入

这种方式比较像nacos的@EnableDiscoveryClient,Feign的@EnableFeignClients 之类。原谅我比较菜,用jedis举个例子。
项目结构
MyRedisTemplateAnno 主要配置类,相当于我们组件的入口
扫描到 com.zjq.jartest.service2 这个包下需要装配的类

@Configuration
@ComponentScan(value = "com.zjq.jartest.service2")
public class MyRedisTemplateAnno {

    private JedisPool jedisPool;

    @PostConstruct
    public void init() {
        GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
        poolConfig.setMaxTotal(500);
        jedisPool = new JedisPool(poolConfig, "127.0.0.1",
                6379, 5000, "123456", 1);
    }

    public void insert(String k, String v) {
        Jedis jedis = jedisPool.getResource();
        jedis.set(k, v);
        jedis.close();
    }

}

其中,第一行是声明为一个配置类
第二行为设置自动扫描包,让Spring能够发现我们封装的组件的其他 Spring Bean

到这儿还结束,我们的目的是使用者通过注解才能发现该配置类(类似于nacos和feign那样),所以我们还需要建立一个注解类,此处取名为 EnableMyRedisCilent(是不是起名很规范~)

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Documented
@Import({MyRedisTemplateAnno.class})
public @interface EnableMyRedisCilent {

}

重点是**@Import** 这个注解,引入上面的配置类。

这样使用者在启动类上加入 @EnableMyRedisCilent 这个注解就可以了

@SpringBootApplication
@EnableMyRedisCilent
public class ExceltonijingliApplication {

    public static void main(String[] args) {
        SpringApplication.run(ExceltonijingliApplication.class, args);
    }
}

或者在其他类上加上

@EnableMyRedisCilent
@Configuration
public class TestConfig {
}

4.利用SPI机制注入

java spi的具体约定为:当服务的提供者,提供了服务接口的一种实现之后,在jar包的META-INF/services/目录里同时创建一个以服务接口命名的文件。该文件里就是实现该服务接口的具体实现类。而当外部程序装配这个模块的时候,就能通过该jar包META-INF/services/里的配置文件找到具体的实现类名,并装载实例化,完成模块的注入。 基于这样一个约定就能很好的找到服务接口的实现类,而不需要再代码里制定。jdk提供服务实现查找的一个工具类java.util.ServiceLoader
典型的应用就是dubbo。

在这里插入图片描述
此方法最关键的为 resources/META-INF/spring.factories 文件,当项目启动时,Spring会扫描所有jar包下面的 spring.factories 文件,进行相应的自动配置处理。

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.zjq.jartest.service.MyRedisTemplate

其中 org.springframework.boot.autoconfigure.EnableAutoConfiguration 代表自动配置的 key,即代表需要自动配置哪些类,\ 可以理解为一个换行符,则该行下面的每行当做一个参数

MyRedisTemplate 类,不用加注解

public class MyRedisTemplate {
    private JedisPool jedisPool;
    
    @PostConstruct
    public void init() {
        GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
        poolConfig.setMaxTotal(500);
        this.jedisPool = new JedisPool(poolConfig, "127.0.0.1",
                6379, 5000, "123456", 1);
    }

    public void insert(String k, String v) {
        Jedis jedis = jedisPool.getResource();
        jedis.set(k, v);
        jedis.close();
    }

5.打包测试

首先是我们的jartest的pom

  1. 这里需要注意的是我这里打包选举的是maven的方式,而非springboot的方式。
  2. 因为上文中提到需要用到注解方式注释,所以加上了spring的依赖。
  3. 如果光使用spi机制,不需要加入spring的依赖。
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.zjq.jartest</groupId>
    <artifactId>jartest</artifactId>
    <version>1.0.0-Alpha</version>
    <name>jartest</name>
    <description>第三方中间件jar测试</description>
    
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.1.8.RELEASE</version>
            <!-- 如果该项目是准备作为一个第三方插件的话,这里对spring的依赖范围最好指定为provided-->
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.7.2</version>
        </dependency>
    </dependencies>

    <!--普通的jar 公共模块不要用上面的springboot构建 打成可执行的jar -->
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

使用者在工程中引入

        <!--jar test 内部测试版-->
        <dependency>
            <groupId>com.zjq.jartest</groupId>
            <artifactId>jartest</artifactId>
            <version>1.0.0-Alpha</version>
        </dependency>

springboot测试类

    /**
     *  用 spi 方式 注入
     */
    @Autowired
    private MyRedisTemplate myRedisTemplate;

    @Test
    public void test() {
        System.out.println("start test ");
        myRedisTemplate.insert("myRedisTemplate","12121");
    }

    /**
     *   用注解方式 注入  需要加上@@EnableMyRedisCilent 我们自定义的直接
     */
    @Autowired
    private MyRedisTemplateAnno myRedisTemplateAnno;

    @Test
    public void test2() {
        System.out.println("start  test2 ");
        myRedisTemplateAnno.insert("myRedisTemplateAnno","12121");
    }

到此结束,自己对spring的学习还不是很深刻,比如拿jedis举例,目前还做不向springboot那样自动装配redis,从yml中读取配置之类,总之继续努力~

6.结语

世上无难事,只怕有心人,每天积累一点点,fighting!!!

### Spring Boot 项目打成 ZIP 文件的方法 #### Maven 配置 为了实现Spring Boot 应用程序打为 ZIP 文件,可以通过调整 `pom.xml` 中的配置来完成。具体来说,Maven 的 Assembly 插件可以帮助我们创建自定义的打形式。 以下是完整的 `pom.xml` 配置片段: ```xml <build> <plugins> <!-- Spring Boot Maven Plugin --> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> <!-- Assembly Plugin for creating a zip package --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-assembly-plugin</artifactId> <version>3.4.2</version> <executions> <execution> <phase>package</phase> <goals> <goal>single</goal> </goals> <configuration> <descriptors> <descriptor>src/assembly/zip.xml</descriptor> </descriptors> </configuration> </execution> </executions> </plugin> </plugins> </build> ``` 上述配置引入了 `maven-assembly-plugin` 并指定了一个描述符文件路径 `src/assembly/zip.xml`,用于定义 ZIP 的内容结构[^1]。 --- #### 自定义装配描述符 (Assembly Descriptor) 在项目的 `src/assembly/` 目录下创建名为 `zip.xml` 的文件,其内容如下所示: ```xml <assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3 http://maven.apache.org/xsd/assembly-1.1.3.xsd"> <id>distribution-package</id> <formats> <format>zip</format> </formats> <fileSets> <fileSet> <directory>${project.build.directory}</directory> <outputDirectory>/</outputDirectory> <includes> <include>*.jar</include> </includes> </fileSet> <fileSet> <directory>src/main/resources/config</directory> <outputDirectory>/config</outputDirectory> <includes> <include>*</include> </includes> </fileSet> </fileSets> </assembly> ``` 此 XML 定义了一个 ZIP 文件的结构,其中含了编译后的 JAR 文件以及额外的资源目录(如 `/config`)。可以根据实际需求修改 `<fileSet>` 来控制哪些文件被含到最终的 ZIP 中。 --- #### 构建命令 执行以下命令即可生成 ZIP : ```bash mvn clean package ``` 构建完成后,可以在目标目录找到形如 `${project.artifactId}-${project.version}-distribution-package.zip` 的文件。 --- #### 动态生成 ZIP 文件的功能扩展 如果希望应用程序运行时动态生成 ZIP 文件,则可以参考以下代码示例。通过 Java 的标准库或者第三方工具类库(如 Apache Commons Compress),能够轻松实现这一功能。 ##### 使用 JDK 原生 API 实现 ZIP 打 ```java import java.io.*; import java.nio.file.Files; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class ZipUtil { public static void createZip(String sourceDirPath, String zipFilePath) throws IOException { File dir = new File(sourceDirPath); try ( FileOutputStream fos = new FileOutputStream(zipFilePath); ZipOutputStream zos = new ZipOutputStream(fos) ) { addFilesToZip(dir, "", zos); } } private static void addFilesToZip(File fileToAdd, String parentPath, ZipOutputStream zos) throws IOException { if (fileToAdd.isDirectory()) { for (File child : Objects.requireNonNull(fileToAdd.listFiles())) { addFilesToZip(child, parentPath + fileToAdd.getName() + "/", zos); } } else { try (InputStream is = Files.newInputStream(fileToAdd.toPath())) { ZipEntry entry = new ZipEntry(parentPath + fileToAdd.getName()); zos.putNextEntry(entry); byte[] buffer = new byte[1024]; int length; while ((length = is.read(buffer)) >= 0) { zos.write(buffer, 0, length); } zos.closeEntry(); } } } } ``` 调用方法时传入源目录和目标 ZIP 文件路径即可完成打操作[^2]。 --- #### 第三方库支持 对于更复杂的场景,推荐使用 **Apache Commons Compress** 或其他成熟的压缩库简化开发工作量。例如: ```xml <!-- 添加依赖 --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-compress</artifactId> <version>1.21</version> </dependency> ``` 利用该库可进一步优化性能与兼容性[^3]。 ---
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值