SpringBoot中自定义starter实例与原理

1 自定义启动器

本文首先提出以下开发需求:需要自定义一个启动器spring-boot-football-starter,业务方引入这个启动器之后可以直接使用Football实例。


1.1 创建项目

1.1.1 项目名

java-front-football-starter

1.1.2 springboot版本号

<dependency>
    <artifactId>spring-boot-dependencies</artifactId>
    <groupId>org.springframework.boot</groupId>
    <scope>import</scope>
    <type>pom</type>
    <version>2.1.7.RELEASE</version>
</dependency>

1.2 创建Football

@Getter
@Setter
public class Football {
    private String a;
    private String b;
}

1.3 创建配置类

@Getter
@Setter
@ConfigurationProperties(prefix = "football") // prefix不支持驼峰命名
public class FootballProperties {
    private boolean enable = true;
    private String a;
    private String b;
}

1.4 创建AutoConfiguration

@Slf4j
@Configuration
@ConditionalOnClass(Football.class) // 只有当classpath中存在Football类时才实例化本类
@EnableConfigurationProperties(FootballProperties.class)
public class FootballAutoConfiguration {

    @Autowired
    private FootballProperties footballProperties;

    @Bean
    @ConditionalOnMissingBean(Football.class) // 只有当容器不存在其它Football实例时才使用此实例
    public Football football() {
        if (!footballProperties.isEnable()) {
            String defaultValue = "default";
            Football football = new Football();
            football.setA(defaultValue);
            football.setB(defaultValue);
            log.info("==========football close bean={}==========", JSON.toJSONString(football));
            return football;
        }
        Football football = new Football();
        football.setA(footballProperties.getA());
        football.setB(footballProperties.getB());
        log.info("==========football open bean={}==========", JSON.toJSONString(football));
        return football;
    }
}

  • 条件注解说明
@ConditionalOnBean
只有在当前上下文中存在某个对象时才进行实例化Bean

@ConditionalOnClass
只有classpath中存在class才进行实例化Bean

@ConditionalOnExpression
只有当表达式等于true才进行实例化Bean

@ConditionalOnMissingBean
只有在当前上下文中不存在某个对象时才进行实例化Bean

@ConditionalOnMissingClass
某个class类路径上不存在时才进行实例化Bean

@ConditionalOnNotWebApplication
当前应用不是WEB应用才进行实例化Bean

1.5 spring.factories

  • 工厂文件位置
- src/main/resources
    - META-INF
        -spring.factories

  • 工厂文件内容
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.java.front.football.starter.configuration.FootballAutoConfiguration

2 测试启动器

2.1 引入依赖

<dependency>
    <groupId>com.java.test</groupId>
    <artifactId>java-front-football-starter</artifactId>
    <version>1.0.0</version>
</dependency>

2.2 application.yml

server:
  port: 9999
football:
  enable: true
  a: "aaa"
  b: "bbb"

2.3 TestController

@RestController
@RequestMapping("/test/football")
public class TestController {

    @Resource
    private Football football;

    @GetMapping
    public Football get() {
        return football;
    }
}

2.4 TestApplication

@SpringBootApplication
public class TestApplication {

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

2.5 测试用例

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT, classes = TestApplication.class)
@RunWith(SpringJUnit4ClassRunner.class)
public class TestControllerTest {

    @Test
    public void test() {
        String response = HttpUtil.get("http://localhost:9999/test/football");
        Assert.assertTrue(!StringUtils.isEmpty(response));
    }
}

2.6 测试结果

==========football open bean={"a":"aaa","b":"bbb"}==========

3 原理分析

  • 启动类
@SpringBootApplication
public class TestApplication {

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

  • SpringBootApplication
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class), @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class)})
public @interface SpringBootApplication {
    //......
}

  • EnableAutoConfiguration
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import(AutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {
    //......
}

  • AutoConfigurationImportSelector
public class AutoConfigurationImportSelector implements DeferredImportSelector, BeanClassLoaderAware, ResourceLoaderAware, BeanFactoryAware, EnvironmentAware, Ordered {

    protected AutoConfigurationEntry getAutoConfigurationEntry(AutoConfigurationMetadata autoConfigurationMetadata,
            AnnotationMetadata annotationMetadata) {
        if (!isEnabled(annotationMetadata)) {
            return EMPTY_ENTRY;
        }
        AnnotationAttributes attributes = getAttributes(annotationMetadata);
        // 加载配置
        List<String> configurations = getCandidateConfigurations(annotationMetadata, attributes);
        configurations = removeDuplicates(configurations);
        Set<String> exclusions = getExclusions(annotationMetadata, attributes);
        checkExcludedClasses(configurations, exclusions);
        configurations.removeAll(exclusions);
        configurations = filter(configurations, autoConfigurationMetadata);
        fireAutoConfigurationImportEvents(configurations, exclusions);
        return new AutoConfigurationEntry(configurations, exclusions);
    }
}

  • getCandidateConfigurations
public class AutoConfigurationImportSelector implements DeferredImportSelector, BeanClassLoaderAware, ResourceLoaderAware, BeanFactoryAware, EnvironmentAware, Ordered {

    protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
        List<String> configurations = SpringFactoriesLoader.loadFactoryNames(getSpringFactoriesLoaderFactoryClass(), getBeanClassLoader());
        Assert.notEmpty(configurations, "No auto configuration classes found in META-INF/spring.factories. If you are using a custom packaging, make sure that file is correct.");
        return configurations;
    }
}

  • loadFactoryNames
public final class SpringFactoriesLoader {

    // 工厂加载路径
    public static final String FACTORIES_RESOURCE_LOCATION = "META-INF/spring.factories";

    public static List<String> loadFactoryNames(Class<?> factoryClass, @Nullable ClassLoader classLoader) {
        String factoryClassName = factoryClass.getName();
        return loadSpringFactories(classLoader).getOrDefault(factoryClassName, Collections.emptyList());
    }

    private static Map<String, List<String>> loadSpringFactories(@Nullable ClassLoader classLoader) {
        MultiValueMap<String, String> result = cache.get(classLoader);
        if (result != null) {
            return result;
        }
        try {
            // 根据路径加载工厂信息(FootballAutoConfiguration)
            Enumeration<URL> urls = (classLoader != null ? classLoader.getResources(FACTORIES_RESOURCE_LOCATION) : ClassLoader.getSystemResources(FACTORIES_RESOURCE_LOCATION));
            result = new LinkedMultiValueMap<>();
            while (urls.hasMoreElements()) {
                URL url = urls.nextElement();
                UrlResource resource = new UrlResource(url);
                Properties properties = PropertiesLoaderUtils.loadProperties(resource);
                for (Map.Entry<?, ?> entry : properties.entrySet()) {
                    String factoryClassName = ((String) entry.getKey()).trim();
                    for (String factoryName : StringUtils.commaDelimitedListToStringArray((String) entry.getValue())) {
                        result.add(factoryClassName, factoryName.trim());
                    }
                }
            }
            cache.put(classLoader, result);
            return result;
        } catch (IOException ex) {
            throw new IllegalArgumentException("Unable to load factories from location [" FACTORIES_RESOURCE_LOCATION + "]", ex);
        }
    }
}

4 延伸知识

4.1 spring官方启动器

https://docs.spring.io/spring-boot/docs/2.1.7.RELEASE/reference/html/using-boot-build-systems.html#using-boot-starter

  • 英文介绍

Starters are a set of convenient dependency descriptors that you can include in your application. You get a one-stop shop for all the Spring and related technologies that you need without having to hunt through sample code and copy-paste loads of dependency descriptors. For example, if you want to get started using Spring and JPA for database access, include the spring-boot-starter-data-jpa dependency in your project


  • 中文介绍

Starter是一组方便的依赖描述符,你可以将其包含在应用程序中。你可以一站式获得所有所需的Spring和相关技术,而无需在示例代码中搜索并复制粘贴大量依赖描述符。如果你想要开始使用Spring和JPA进行数据库访问,请在项目中包含spring-boot-starter-data-jpa依赖项


4.2 spring-boot-starter

这个启动器是核心启动器,功能包括自动配置支持、日志记录和YAML。任意引入一个启动器点击分析,最终发现引用核心启动器。

  • 引用spring-boot-starter-data-redis
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

  • 发现引用spring-boot-starter
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
    <version>2.1.7.RELEASE</version>
    <scope>compile</scope>
</dependency>

  • 发现引用spring-boot-autoconfigure
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-autoconfigure</artifactId>
    <version>2.1.7.RELEASE</version>
    <scope>compile</scope>
</dependency>

  • 工厂文件位置
/META-INF/spring.factories

  • 文件中指定Redis自动配置
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration

  • 自动装配类RedisAutoConfiguration
@Configuration
@ConditionalOnClass(RedisOperations.class)
@EnableConfigurationProperties(RedisProperties.class) // 配置信息类
@Import({ LettuceConnectionConfiguration.class, JedisConnectionConfiguration.class })
public class RedisAutoConfiguration {
    //......
}

  • 配置信息类RedisProperties
@ConfigurationProperties(prefix = "spring.redis")
public class RedisProperties {
    private int database = 0;
    private String url;
    private String host = "localhost";
    private String password;
    private int port = 6379;
    //......
}

  • application.yml文件配置
spring
    redis
        host:xxx
        port:xxx
        password:xxx

4.3 第三方启动器

如果使用第三方启动器,如何知道在yml文件中设置什么配置项?本章节以mybatis为例:

  • 引入mybatis-spring-boot-starter
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.2.3</version>
</dependency>

  • 自动装配依赖
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-autoconfigure</artifactId>
</dependency>

  • 工厂文件位置
/META-INF/spring.factories

  • 文件中指定MyBatis自动配置
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration

  • 自动配置类MybatisAutoConfiguration
@ConditionalOnClass({ SqlSessionFactory.class, SqlSessionFactoryBean.class })
@ConditionalOnSingleCandidate(DataSource.class)
@EnableConfigurationProperties(MybatisProperties.class) // 配置信息类
@AutoConfigureAfter({ DataSourceAutoConfiguration.class, MybatisLanguageDriverAutoConfiguration.class })
public class MybatisAutoConfiguration implements InitializingBean {
    //......
}

  • 配置信息类MybatisProperties
@ConfigurationProperties(prefix = MybatisProperties.MYBATIS_PREFIX)
public class MybatisProperties {
    public static final String MYBATIS_PREFIX = "mybatis";
    private String configLocation;
    private String[] mapperLocations;
    private String typeAliasesPackage;
    private Class<?> typeAliasesSuperType;
    //......
}

  • application.yml文件配置
mybatis:
  mapperLocations: classpath:db/sqlmappers/*.xml
  configLocation: classpath:db/mybatis-config.xml

5 文章总结

第一章节介绍如何自定义一个简单启动器,第二章节对自定义启动器进行测试,第三章节通过源码分析介绍启动器运行原理,第四章进行知识延伸介绍spring官方启动器,使用第三方启动器相关知识,希望本文对大家有所帮助。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是一个简单的Spring Boot自定义Starter的示例,该Starter实现了一个自定义的HelloWorld功能: 1. 创建Maven项目 首先,我们需要创建一个Maven项目作为我们自定义Starter的项目。在项目的pom.xml添加Spring Boot的依赖,以及其他需要集成的依赖。 2. 编写自动配置类 在src/main/java目录下创建一个名为HelloWorldAutoConfiguration的类,该类用于自动配置HelloWorld功能: ```java @Configuration @ConditionalOnClass(HelloWorldService.class) @EnableConfigurationProperties(HelloWorldProperties.class) public class HelloWorldAutoConfiguration { @Autowired private HelloWorldProperties properties; @Bean @ConditionalOnMissingBean public HelloWorldService helloWorldService() { HelloWorldService service = new HelloWorldService(); service.setMsg(properties.getMsg()); return service; } @ConfigurationProperties(prefix = "hello.world") public static class HelloWorldProperties { private String msg = "Hello, world!"; public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } } } ``` 上述代码,@Configuration注解表示该类是一个配置类,@ConditionalOnClass注解表示只有当HelloWorldService类存在时才进行配置,@EnableConfigurationProperties注解表示将HelloWorldProperties类注入到Spring容器。在helloWorldService方法,我们通过读取HelloWorldProperties的配置来创建一个HelloWorldService实例。 3. 编写Starter类 在src/main/java目录下创建一个名为HelloWorldStarter的类,该类用于将自动配置类注入到Spring容器: ```java @Configuration @EnableConfigurationProperties(HelloWorldProperties.class) @Import(HelloWorldAutoConfiguration.class) public class HelloWorldStarter { } ``` 上述代码,@Configuration注解表示该类是一个配置类,@EnableConfigurationProperties注解表示将HelloWorldProperties类注入到Spring容器,@Import注解表示将HelloWorldAutoConfiguration类注入到Spring容器。 4. 打包和发布Starter 在命令行运行以下命令,将自定义Starter打包成jar包: ``` mvn clean package ``` 然后将jar包发布到Maven仓库。 5. 在项目使用自定义Starter 在其他Spring Boot项目的pom.xml文件添加以下依赖: ```xml <dependency> <groupId>com.example</groupId> <artifactId>hello-world-starter</artifactId> <version>1.0.0</version> </dependency> ``` 在项目使用以下代码来测试自定义Starter是否生效: ```java @RestController public class TestController { @Autowired private HelloWorldService helloWorldService; @GetMapping("/hello") public String hello() { return helloWorldService.sayHello(); } } ``` 上述代码,我们通过@Autowired注解注入了HelloWorldService实例,并在hello方法调用了sayHello方法来测试自定义Starter是否生效。 以上就是Spring Boot自定义Starter的一个简单示例,通过自定义Starter,我们可以将自己的功能快速集成到Spring Boot,提高开发效率。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值