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

四. 自定义启动器

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

四. 自定义启动器

四. 自定义启动器

当需要把一些共用的 api 封装成 jar 包的时候,就可以尝试自定义启动 器来做。

自定义启动器用到的就是 springboot 中的 SPI 原理,springboot 会去加载 meta-INF/spring.factories 配置文件。加载 EnableAutoConfiguration 为 key 的所有类。

利用这一点,我们也可以定义一个工程也会有这个文件。

1、定义启动器核心工程 工程结构
custom-spring-boot-starter-autoconfigurer
    ─src
        └─main
            ├─java
            │  └─len
            │      └─hgy
            │          │  CustomSpringBootStarterAutoconfigurerApplication.java
            │          │
            │          └─start
            │                  CustomStarterRun.java
            │                  JackTemplate.java
            │                  RedisConfig.java
            │
            └─resources
                │  application.properties
                │
                └─meta-INF
                        spring.factories
spring.factories 配置内容
org.springframework.boot.autoconfigure.EnableAutoConfiguration=
len.hgy.start.CustomStarterRun
被 springboot SPI 加载的类
@Configuration
@ConditionalOnClass(MyTemplate.class)
@EnableConfigurationProperties(RedisConfig.class)
public class CustomStarterRun {

    @Autowired
    private RedisConfig redisConfig;

    @Bean
    public MyTemplate jackTemplate() {
        return new MyTemplate(redisConfig);
    }
}

这个 MyTemplate 实例就是我们封装的通用 API,其他工程可以直接导入 jar 使用的。

2、自定义 starter

我们还会定义一个没代码的工程,在这个工程里面没有任何代码,只有一个 pom 文件。Pom 里面就是对前面核心工程 jar 包的导入

工程结构:

springboot-starter-mytemplate
	│  pom.xml

pom.xml




  4.0.0

  
    org.springframework.boot
    spring-boot-starter-parent
    2.2.2.RELEASE
     
  

  len.hgy
  spring-boot-starter-template
  1.0-SNAPSHOT

  jackTemplate-spring-boot-starter
  
  http://www.example.com

  
    UTF-8
    1.8
    1.8
  
  
    
      len.hgy
      custom-spring-boot-starter-autoconfigurer
      0.0.1-SNAPSHOT
    
  

主类

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

打包

mvn clean package -Dmaven.test.skip=true

运行

java -jar spring-boot-starter-template-1.0-SNAPSHOT.jar
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/723458.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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