Spring Boot扩展机制 - Spring Factories

2020-09-17 16:11:07 浏览数 (1)

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

使用方式

  • 启动类:com.tenmao.FactoriesApplication
代码语言:javascript复制
@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
代码语言:javascript复制
@Configuration
public class ShimaoAuthConfiguration {
    @Bean
    public UserManager userManager() {
        return new UserManager();
    }
}
  • 扩展配置:META-INF/spring.factories
代码语言:javascript复制
org.springframework.boot.autoconfigure.EnableAutoConfiguration=
com.shimao.ShimaoAuthConfiguration

shardingsphere扩展

  • org.apache.shardingsphere.shardingjdbc.spring.boot.SpringBootConfiguration
代码语言:javascript复制
@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
代码语言:javascript复制
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扩展
代码语言:javascript复制
# 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

参考

  • Spring Boot的扩展机制之Spring Factories
  • 利用spring.factories机制加载Bean

0 人点赞