Spring Boot扩展机制 - Spring Factories

时间:2022-07-25
本文章向大家介绍Spring Boot扩展机制 - Spring Factories,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

Spring Boot使用的时候,有时候为业务方提供一些基础服务,比如监控,告警等,为了降低业务接入难度,就需要使用Spring Factories扩展机制

使用方式

  • 启动类:com.tenmao.FactoriesApplication
@SpringBootApplication
public class FactoriesApplication implements ApplicationRunner {

    @Resource
    private UserManager userManager;

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

    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println(userManager.getName());
    }
}
  • 配置类:com.shimao.ShimaoAuthConfiguration
@Configuration
public class ShimaoAuthConfiguration {
    @Bean
    public UserManager userManager() {
        return new UserManager();
    }
}
  • 扩展配置:META-INF/spring.factories
org.springframework.boot.autoconfigure.EnableAutoConfiguration=
com.shimao.ShimaoAuthConfiguration

shardingsphere扩展

  • org.apache.shardingsphere.shardingjdbc.spring.boot.SpringBootConfiguration
@Configuration
@EnableConfigurationProperties({
        SpringBootShardingRuleConfigurationProperties.class, 
        SpringBootMasterSlaveRuleConfigurationProperties.class, SpringBootEncryptRuleConfigurationProperties.class, SpringBootPropertiesConfigurationProperties.class})
@ConditionalOnProperty(prefix = "spring.shardingsphere", name = "enabled", havingValue = "true", matchIfMissing = true)
@AutoConfigureBefore(DataSourceAutoConfiguration.class)
@RequiredArgsConstructor
public class SpringBootConfiguration implements EnvironmentAware {
    //忽略了其他
}
  • spring.factories
org.springframework.boot.autoconfigure.EnableAutoConfiguration=
org.apache.shardingsphere.shardingjdbc.spring.boot.SpringBootConfiguration

其他常见第三方库

这些库都用到Spring Factories扩展机制

  • sharding-jdbc-spring-boot-starte
  • mybatis-plus-boot-starter
  • redisson

其他扩展点

  • Sprig Boot扩展
# Auto Configure(这个扩展是使用的最多的,特别是是一些公共SDK,会这借助这扩展实现Bean的自动注入)
org.springframework.boot.autoconfigure.EnableAutoConfiguration

# PropertySource Loaders
org.springframework.boot.env.PropertySourceLoader

# Run Listeners
org.springframework.boot.SpringApplicationRunListener

# Error Reporters
org.springframework.boot.SpringBootExceptionReporter

# Application Context Initializers
org.springframework.context.ApplicationContextInitializer

# Application Listeners
org.springframework.context.ApplicationListener

# Environment Post Processors
org.springframework.boot.env.EnvironmentPostProcessor

# Failure Analyzers
org.springframework.boot.diagnostics.FailureAnalyzer

# FailureAnalysisReporters
org.springframework.boot.diagnostics.FailureAnalysisReporter

参考