在实际开发中,仅靠SpringBoot的自动配置是远远不够的,比如要访问多个数据源,自动配置就完全无能为力了。
自动配置的本质
本质就是在容器中预配置要整合的框架所需的基础Bean。
以MyBatis为例,spring整合MyBatis无非就是完成以下事情:
- 配置SqlSessionFactory Bean,当然,该Bean需要注入一个DataSource
- 配置SqlSessionTemplate Bean,将上面的SqlSessionFactory 注入该Bean
- 注册Mapper组件的自动扫描,相当于添加元素
自动配置非常简单,无非就是有框架提供一个@Configuration修饰的配置类(相当于传统的xml配置文件),在该配置类中用@Bean预先配置默认的SqlSessionFactory、SqlSessionTemplate,并注册Mapper组件的自动扫描即可。
比如MybatisAutoConfiguration源代码:- @Configuration // 被修饰的类变成配置类
- // 当SqlSessionFactory、SqlSessionFactoryBean类存在时,才会生效。
- // 条件注解之一
- @ConditionalOnClass({SqlSessionFactory.class, SqlSessionFactoryBean.class})
- // 当DataSource Bean存在时,才会生效
- // 条件注解之一
- @ConditionalOnSingleCandidate(DataSource.class)
- // 启用Mybatis的属性处理类
- // 启动属性处理类
- @EnableConfigurationProperties({MybatisProperties.class})
- //指定该配置类在DataSourceAutoConfiguration和MybatisLanguageDriverAutoConfiguration之后加载
- @AutoConfigureAfter({DataSourceAutoConfiguration.class, MybatisLanguageDriverAutoConfiguration.class})
- // 实现 InitializingBean 接口,该接口中的 afterPropertiesSet 方法会在该Bean初始化完成后被自动调用
- public class MybatisAutoConfiguration implements InitializingBean {
- private static final Logger logger = LoggerFactory.getLogger(org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration.class);
- // Mybatis的配置属性
- private final MybatisProperties properties;
- // Mybatis的拦截器、类型处理器、语言驱动等
- private final Interceptor[] interceptors;
- private final TypeHandler[] typeHandlers;
- private final LanguageDriver[] languageDrivers;
- private final ResourceLoader resourceLoader;
- private final DatabaseIdProvider databaseIdProvider;
- private final List<ConfigurationCustomizer> configurationCustomizers;
- private final List<SqlSessionFactoryBeanCustomizer> sqlSessionFactoryBeanCustomizers;
- public MybatisAutoConfiguration(MybatisProperties properties, ObjectProvider<Interceptor[]> interceptorsProvider, ObjectProvider<TypeHandler[]> typeHandlersProvider, ObjectProvider<LanguageDriver[]> languageDriversProvider, ResourceLoader resourceLoader, ObjectProvider<DatabaseIdProvider> databaseIdProvider, ObjectProvider<List<ConfigurationCustomizer>> configurationCustomizersProvider, ObjectProvider<List<SqlSessionFactoryBeanCustomizer>> sqlSessionFactoryBeanCustomizers) {
- this.properties = properties;
- this.interceptors = (Interceptor[])interceptorsProvider.getIfAvailable();
- this.typeHandlers = (TypeHandler[])typeHandlersProvider.getIfAvailable();
- this.languageDrivers = (LanguageDriver[])languageDriversProvider.getIfAvailable();
- this.resourceLoader = resourceLoader;
- this.databaseIdProvider = (DatabaseIdProvider)databaseIdProvider.getIfAvailable();
- this.configurationCustomizers = (List)configurationCustomizersProvider.getIfAvailable();
- this.sqlSessionFactoryBeanCustomizers = (List)sqlSessionFactoryBeanCustomizers.getIfAvailable();
- }
- // 在Bean初始化完成后调用该方法
- public void afterPropertiesSet() {
- this.checkConfigFileExists();
- }
- // 检查Mybatis配置文件是否存在
- private void checkConfigFileExists() {
- if (this.properties.isCheckConfigLocation() && StringUtils.hasText(this.properties.getConfigLocation())) {
- // 获取配置文件的资源
- Resource resource = this.resourceLoader.getResource(this.properties.getConfigLocation());
- // 如果resource.exists()方法返回false,则抛出异常
- Assert.state(resource.exists(), "Cannot find config location: " + resource + " (please add config file or check your Mybatis configuration)");
- }
- }
- // 创建SqlSessionFactory Bean
- @Bean
- // 当没有SqlSessionFactory Bean时才会创建
- @ConditionalOnMissingBean
- public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
- // 创建SqlSessionFactoryBean实例
- SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
- // 注入数据源
- factory.setDataSource(dataSource);
- factory.setVfs(SpringBootVFS.class);
- // 如果配置文件路径不为空,则设置配置文件位置
- if (StringUtils.hasText(this.properties.getConfigLocation())) {
- factory.setConfigLocation(this.resourceLoader.getResource(this.properties.getConfigLocation()));
- }
- this.applyConfiguration(factory);
- // 如果配置属性不为空,则设置配置属性
- if (this.properties.getConfigurationProperties() != null) {
- factory.setConfigurationProperties(this.properties.getConfigurationProperties());
- }
- // 应用所有的拦截器
- if (!ObjectUtils.isEmpty(this.interceptors)) {
- factory.setPlugins(this.interceptors);
- }
- // 应用所有databaseIdProvider
- if (this.databaseIdProvider != null) {
- factory.setDatabaseIdProvider(this.databaseIdProvider);
- }
- // 根据包名应用TypeAliases
- if (StringUtils.hasLength(this.properties.getTypeAliasesPackage())) {
- factory.setTypeAliasesPackage(this.properties.getTypeAliasesPackage());
- }
- // 根据父类型应用TypeAliases
- if (this.properties.getTypeAliasesSuperType() != null) {
- factory.setTypeAliasesSuperType(this.properties.getTypeAliasesSuperType());
- }
- // 根据包名应用TypeHandler
- if (StringUtils.hasLength(this.properties.getTypeHandlersPackage())) {
- factory.setTypeHandlersPackage(this.properties.getTypeHandlersPackage());
- }
- // 应用所有TypeHandler
- if (!ObjectUtils.isEmpty(this.typeHandlers)) {
- factory.setTypeHandlers(this.typeHandlers);
- }
- // 设置mapper的加载位置
- if (!ObjectUtils.isEmpty(this.properties.resolveMapperLocations())) {
- factory.setMapperLocations(this.properties.resolveMapperLocations());
- }
- Set<String> factoryPropertyNames = (Set) Stream.of((new BeanWrapperImpl(SqlSessionFactoryBean.class)).getPropertyDescriptors()).map(FeatureDescriptor::getName).collect(Collectors.toSet());
- Class<? extends LanguageDriver> defaultLanguageDriver = this.properties.getDefaultScriptingLanguageDriver();
- if (factoryPropertyNames.contains("scriptingLanguageDrivers") && !ObjectUtils.isEmpty(this.languageDrivers)) {
- factory.setScriptingLanguageDrivers(this.languageDrivers);
- if (defaultLanguageDriver == null && this.languageDrivers.length == 1) {
- defaultLanguageDriver = this.languageDrivers[0].getClass();
- }
- }
- if (factoryPropertyNames.contains("defaultScriptingLanguageDriver")) {
- factory.setDefaultScriptingLanguageDriver(defaultLanguageDriver);
- }
- this.applySqlSessionFactoryBeanCustomizers(factory);
- // 返回SqlSessionFactory对象
- return factory.getObject();
- }
- private void applyConfiguration(SqlSessionFactoryBean factory) {
- org.apache.ibatis.session.Configuration configuration = this.properties.getConfiguration();
- if (configuration == null && !StringUtils.hasText(this.properties.getConfigLocation())) {
- configuration = new org.apache.ibatis.session.Configuration();
- }
- if (configuration != null && !CollectionUtils.isEmpty(this.configurationCustomizers)) {
- Iterator var3 = this.configurationCustomizers.iterator();
- while(var3.hasNext()) {
- ConfigurationCustomizer customizer = (ConfigurationCustomizer)var3.next();
- customizer.customize(configuration);
- }
- }
- factory.setConfiguration(configuration);
- }
- private void applySqlSessionFactoryBeanCustomizers(SqlSessionFactoryBean factory) {
- if (!CollectionUtils.isEmpty(this.sqlSessionFactoryBeanCustomizers)) {
- Iterator var2 = this.sqlSessionFactoryBeanCustomizers.iterator();
- while(var2.hasNext()) {
- SqlSessionFactoryBeanCustomizer customizer = (SqlSessionFactoryBeanCustomizer)var2.next();
- customizer.customize(factory);
- }
- }
- }
- // 创建SqlSessionTemplate Bean
- @Bean
- // 当没有SqlSessionTemplate Bean时才会创建
- @ConditionalOnMissingBean
- public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
- ExecutorType executorType = this.properties.getExecutorType();
- // 如果executorType不为null,则创建SqlSessionTemplate时使用该executorType
- return executorType != null ? new SqlSessionTemplate(sqlSessionFactory, executorType) : new SqlSessionTemplate(sqlSessionFactory);
- }
- @Configuration
- // 导入MapperScannerRegistrarNotFoundConfiguration注册类
- @Import({org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration.AutoConfiguredMapperScannerRegistrar.class})
- // 当MapperFactoryBean和MapperScannerConfigurer都不存在时,才会生效
- @ConditionalOnMissingBean({MapperFactoryBean.class, MapperScannerConfigurer.class})
- // 实现 InitializingBean 接口,该接口中的 afterPropertiesSet 方法会在该Bean初始化完成后被自动调用
- public static class MapperScannerRegistrarNotFoundConfiguration implements InitializingBean {
- public MapperScannerRegistrarNotFoundConfiguration() {
- }
- // 重写afterPropertiesSet方法
- public void afterPropertiesSet() {
- org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration.logger.debug("Not found configuration for registering mapper bean using @MapperScan, MapperFactoryBean and MapperScannerConfigurer.");
- }
- }
- // 注册Mapper扫描器的自动配置类
- // 实现 BeanFactoryAware接口可访问spring容器、
- // 实现ImportBeanDefinitionRegistrar 接口可配置额外的bean
- public static class AutoConfiguredMapperScannerRegistrar implements BeanFactoryAware, EnvironmentAware, ImportBeanDefinitionRegistrar {
- // BeanFactory对象,用于保存Spring容器
- private BeanFactory beanFactory;
- private Environment environment;
- public AutoConfiguredMapperScannerRegistrar() {
- }
- public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
- if (!AutoConfigurationPackages.has(this.beanFactory)) {
- org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration.logger.debug("Could not determine auto-configuration package, automatic mapper scanning disabled.");
- } else {
- org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration.logger.debug("Searching for mappers annotated with @Mapper");
- // 获取自动配置要处理的包
- List<String> packages = AutoConfigurationPackages.get(this.beanFactory);
- if (org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration.logger.isDebugEnabled()) {
- packages.forEach((pkg) -> {
- org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration.logger.debug("Using auto-configuration base package '{}'", pkg);
- });
- }
- // 创建BeanDefinitionBuilder对象
- // 它帮助开发者以反射的方式创建任意类的实例
- // 此处就是帮助创建MapperScannerConfigurer类的实例
- BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(MapperScannerConfigurer.class);
- // 为要创建的对象设置属性
- builder.addPropertyValue("processPropertyPlaceHolders", true);
- builder.addPropertyValue("annotationClass", Mapper.class);
- builder.addPropertyValue("basePackage", StringUtils.collectionToCommaDelimitedString(packages));
- BeanWrapper beanWrapper = new BeanWrapperImpl(MapperScannerConfigurer.class);
- Set<String> propertyNames = (Set)Stream.of(beanWrapper.getPropertyDescriptors()).map(FeatureDescriptor::getName).collect(Collectors.toSet());
- if (propertyNames.contains("lazyInitialization")) {
- builder.addPropertyValue("lazyInitialization", "${mybatis.lazy-initialization:false}");
- }
- if (propertyNames.contains("defaultScope")) {
- builder.addPropertyValue("defaultScope", "${mybatis.mapper-default-scope:}");
- }
- boolean injectSqlSession = (Boolean)this.environment.getProperty("mybatis.inject-sql-session-on-mapper-scan", Boolean.class, Boolean.TRUE);
- if (injectSqlSession && this.beanFactory instanceof ListableBeanFactory) {
- ListableBeanFactory listableBeanFactory = (ListableBeanFactory)this.beanFactory;
- Optional<String> sqlSessionTemplateBeanName = Optional.ofNullable(this.getBeanNameForType(SqlSessionTemplate.class, listableBeanFactory));
- Optional<String> sqlSessionFactoryBeanName = Optional.ofNullable(this.getBeanNameForType(SqlSessionFactory.class, listableBeanFactory));
- if (!sqlSessionTemplateBeanName.isPresent() && sqlSessionFactoryBeanName.isPresent()) {
- builder.addPropertyValue("sqlSessionFactoryBeanName", sqlSessionFactoryBeanName.get());
- } else {
- builder.addPropertyValue("sqlSessionTemplateBeanName", sqlSessionTemplateBeanName.orElse("sqlSessionTemplate"));
- }
- }
- builder.setRole(2);
- // 在容器中注册BeanDefinitionBuilder创建的MapperScannerConfigurer对象
- registry.registerBeanDefinition(MapperScannerConfigurer.class.getName(), builder.getBeanDefinition());
- }
- }
- // 获取spring容器和环境对象
- public void setBeanFactory(BeanFactory beanFactory) {
- this.beanFactory = beanFactory;
- }
- public void setEnvironment(Environment environment) {
- this.environment = environment;
- }
- private String getBeanNameForType(Class<?> type, ListableBeanFactory factory) {
- String[] beanNames = factory.getBeanNamesForType(type);
- return beanNames.length > 0 ? beanNames[0] : null;
- }
- }
- }
复制代码 开发WriterTemplate类- # Auto Configure
- org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
- org.mybatis.spring.boot.autoconfigure.MybatisLanguageDriverAutoConfiguration,\
- org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration
复制代码 然后使用 mvn install 命令打成jar包并安装到本地资源库。
在Starter的项目中引入上面的jar包。pom.xml如下:- @Configuration(proxyBeanMethods = false)
- // 仅当com.mysql.cj.jdbc.Driver类存在时该配置类生效
- @ConditionalOnClass(name = "com.mysql.cj.jdbc.Driver")
- public class FkConfig
- {
- @Bean
- public MyBean myBean()
- {
- return new MyBean();
- }
- }
复制代码 然后在开发中编写自定义配置类:- // 仅当容器中不存在名为myService的Bean时,才创建该Bean
- @ConditionalOnMissingBean
- @Bean
- public MyService myService()
- {
- ...
- }
- // 当容器中不存在名为jdbcTemplate的Bean时,才创建该Bean
- @ConditionalOnMissingBean(name="jdbcTemplate")
- @Bean
- public JdbcTemplate JdbcTemplate()
- {
- ...
- }
复制代码 上面代码中的FunnyProperties类- @Configuration(proxyBeanMethods = false)
- public class FkConfig
- {
- @Bean
- // 只有当org.fkjava.test属性具有foo属性值时,下面配置方法才会生效
- @ConditionalOnProperty(name = "test", havingValue = "foo",
- prefix = "org.fkjava")
- public DateFormat dateFormat()
- {
- return DateFormat.getDateInstance();
- }
- }
复制代码 接下来在META-INF/spring.factories文件中注册自动配置类- @SpringBootApplication
- public class App
- {
- public static void main(String[] args)
- {
- // 创建Spring容器、运行Spring Boot应用
- var ctx = SpringApplication.run(App.class, args);
- System.out.println(ctx.getBean("dateFormat"));
- }
- }
复制代码 然后使用 mvn install 命令打成jar包,并安装到maven本地资源库中,就会在自己的本地资源库中找到该jar包,这样就完成了自定义配置的实现。
创建自定义的Starter
一个完整的SpringBoot Starter包含一下两个组件:
- 自动配置模块(auto-configure):包含自动配置类和spring.factories文件
- Starter模块:负责管理自动配置模块和第三方依赖。简而言之,添加本Starter就能使用该自动配置。
由此看出,Starter不包含任何Class文件,只管理愿意来。如果查看官方提供的jar就会发现,它所有自动配置类的Class都由spring-boot-autoconfigure.jar提供,而各个xxx-starter.jar并未提供任何Class文件,只是在这些jar下的相同路径下提供了一个xxx-starter.pom文件,该文件指定Starter管理的自动依赖模块和第三方依赖。
SpringBoot为自动配置包和Starter包提供推荐命名
- 自动配置包的推荐名:xxx-spring-boot
- Starter包的推荐名:xxx-spring-boot-starter
对于第三方Starter不要使用spring-boot-starter-xxx这种方式,这是官方使用的。
有了自定义的Starter后,使用起来和官方的没有区别,比如
添加依赖:在application.properties文件添加配置- @Configuration(proxyBeanMethods = false)
- public class FkConfig
- {
- @Bean
- // 只有当前应用是反应式Web应用时,该配置才会生效
- @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE)
- public DateFormat dateFormat()
- {
- return DateFormat.getDateInstance();
- }
- }
复制代码 主类的代码:- @SpringBootApplication
- public class App
- {
- public static void main(String[] args)
- {
- var app = new SpringApplication(App.class);
- // 设置Web应用的类型,如果不设置则使用默认的类型:
- // 如果有Sping Web依赖,自动是基于Servlet的Web应用
- // 如果有Sping WebFlux依赖,自动是反应式Web应用
- app.setWebApplicationType(WebApplicationType.REACTIVE); // ①
- // 创建Spring容器、运行Spring Boot应用
- var ctx = app.run(args);
- System.out.println(ctx.getBean("dateFormat"));
- }
- }
复制代码 来源:豆瓜网用户自行投稿发布,如果侵权,请联系站长删除 |