自定义Spring Boot自动装配

通常开发人员将通用的逻辑打包到独立JAR文件中,供上层应用使用,不同的运行环境或框架有其独特的SPI机制,作为通用框架的Spring Boot也不例外,当注解@EnableAutoConfiguration激活自动装配后,META/spring.factories资源中声明的@Configuration类随即被装配。

从底层来讲,自动配置(auto-configuration)是通过标准的@Configuration类实现的。此外,@Conditional注解用来约束自动配置生效的条件。通常自动配置类需要使用@ConditionalOnClass和@ConditionalOnMissingBean注解,这是为了确保只有在相关的类被发现及没有声明自定义的@Configuration时才应用自动配置,具体查看spring-boot-autoconfigure源码中的@Configuration类(META-INF/spring.factories文件)。

1、自动装配Class命名的潜规则

通过查看spring-boot-autoconfigure模块内置的自动装配类发现如下规律:

  • ImportAutoConfiguration
  • MessageSourceAutoConfiguration
  • PropertyPlaceholderAutoConfiguration
  • AopAutoConfiguration
  • CacheAutoConfiguration

  • 不难发现所有Spring Boot内建的自动装配类名模式为*AutoConfiguration,该规则无论在Spring Cloud中还是第三方整合中均得以沿用,因此建议创建自己的auto-configuration也依次惯例。

2、自动装配package命名的潜规则

重温@EnableAutoConfiguration在META-INF/spring.factories文件中的配置声明,挑选几个具有代表性的自动装配Class:

org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration
org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration
org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration

明显地发现,三者base package为org.springframework.boot.autoconfigure,不过三种实现类位于不同的模块功能子package下。将讨论的范围扩大至所有Spring Boot内建的自动装配Class,他们的package基本模式为:

org.springframework.boot.autoconfigure
|- ${module-package}
	|- *AutoConfiguration
	|- ${sub-module-package}
		|- ...

其中${module-package}是功能模块package,如web.servlet,而${sub-module-package}是子模块package,如error。

按照此规律自动装配package命名模式应该是:

${root-package}
|- autoconfigure
	|- ${module-package}
		|- *AutoConfiguration
		|- ${sub-module-package}
			|- ...

${root-package}是根package,如com.acme。

3、自定义Spring Boot Starter

一个完整的Spring Boot starter可能包含以下组件:

  • autoconfigure模块,包含自动配置类的代码。
  • starter模块,提供自动配置模块及其他有用的依赖,简而言之,添加本starter就能开始使用该library。

注:如果不需要将它们分离开来,你可以将自动配置代码和依赖管理放到一个单一模块中。

3.1、Spring Boot Starter命名规则

官方推荐开发人员使用${module}-spring-boot-starter的starter命名模式,采用如此命名的Spring Boot Starter属于第三方Starter,而Spring Boot官方的Starter则采用spring-boot-starter-${module}的命名模式。同时开发人员可以将starter发布为 m o d u l e − s p r i n g − b o o t − s t a r t e r 和 {module}-spring-boot-starter和 modulespringbootstarter{module}-spring-boot-autoconfigure两个jar文件。

此外,如果你的starter提供配置keys,需要为它们提供一个合适的命名空间,特别是不要使用Spring Boot的命名空间(比如,server,management,spring等),这些是属于Spring Boot的,可能会在将来以相同方式提高/修改它们,这可能会破坏你的东西。实际上这些命名空间是外部化配置@ConfigurationProperties前缀属性prefix,同时spring-boot-configuration-processor能够帮助@ConfigurationProperties Bean生成IDE辅助元信息:

确保触发meta-data生成,这样IDE辅助也就可以用于你的keys了,你可能想检查生成的元数据(META-INF/spring-configuration-metadata.json)以确保keys被正确的文档化。

3.2、实现Spring Boot Starter

3.2.1、新建Spring Boot Starter工程——formatter-spring-boot-starter

构建一个名为formatter-spring-boot-starter的Maven工程,增加Spring Boot Starter依赖,完整pom如下:

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>spring-boot-2.0-samples</artifactId>
        <groupId>thinking-in-spring-boot</groupId>
        <version>1.0.0-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <groupId>thinking-in-spring-boot</groupId>
    <artifactId>formatter-spring-boot-starter</artifactId>
    <dependencies>

        <!-- Spring Boot Starter 基础依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
            <optional>true</optional>
        </dependency>

        <!-- Jackson 依赖 -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>

    </dependencies>

</project>
3.2.2、新建格式化接口——Formatter
public interface Formatter {

    /**
     * 格式化操作
     *
     * @param object 待格式化对象
     * @return 返回格式化后的内容
     */
    String format(Object object);

}

Formatter的package应该为thinking.in.spring.boot.samples.autoconfigure.formatter,后续其他相关实现也存放于此。

3.2.3、实现Formatter接口——DefaultFormatter
public class DefaultFormatter implements Formatter {

    @Override
    public String format(Object object) {
        return String.valueOf(object); // null 安全实现
    }
}
3.2.4、实现DefaultFormatter自动装配——FormatterAutoConfiguration
@Configuration
@ConditionalOnProperty(prefix = "formatter", name = "enabled", havingValue = "true",
        matchIfMissing = true) // 当属性配置不存在时,同样视作匹配
@ConditionalOnResource(resources = "META-INF/spring.factories")
@ConditionalOnNotWebApplication
@ConditionalOnExpression("${formatter.enabled:true}")
public class FormatterAutoConfiguration {

    /**
     * 构建 {@link DefaultFormatter} Bean
     *
     * @return {@link DefaultFormatter}
     */
    @Bean
    @ConditionalOnMissingClass(value = "com.fasterxml.jackson.databind.ObjectMapper")
    public Formatter defaultFormatter() {
        return new DefaultFormatter();
    }

    /**
     * JSON 格式 {@link Formatter} Bean
     *
     * @return {@link JsonFormatter}
     */
    @Bean
    @ConditionalOnClass(name = "com.fasterxml.jackson.databind.ObjectMapper")
    @ConditionalOnMissingBean(type = "com.fasterxml.jackson.databind.ObjectMapper")
    public Formatter jsonFormatter() {
        return new JsonFormatter();
    }

    @Bean
    @ConditionalOnBean(ObjectMapper.class)
    public Formatter objectMapperFormatter(ObjectMapper objectMapper) {
        return new JsonFormatter(objectMapper);
    }
}
3.2.5、META-INF/spring.factories声明FormatterAutoConfiguration
# FormatterAutoConfiguration 自动装配声明
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
thinking.in.spring.boot.samples.autoconfigure.formatter.FormatterAutoConfiguration

3.3、Spring Boot Starter特殊说明

在实现自定义Spring Boot Starter的pom中,有一处细节有待说明:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
    <optional>true</optional>
</dependency>

其中org.springframework.boot:spring-boot-starter的maven依赖声明为<optional>true</optional>,其目的在于说明formatter-spring-boot-starter不应该传递spring-boot-starter的依赖。一旦starter发布为jar,spring-boot-starter的版本也随之固定。当应用使用该starter后,很有可能与当前应用所依赖的spring-boot-starter版本冲突,由于不同环境下ClassLoader加载的不确定性,最终导致Class文件二进制不兼容的情况,可能表现在IDE中工作正常,而部署在线上却发生故障。由于Spring Boot应用直接或间接地引入spring-boot-starter相关依赖,因此这些依赖不需要也不应该由自定义spring-boot-starter传递引入。

请保持spring-boot-starter等相关依赖声明为<optional>true</optional>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值