flyway从入门到精通(七):spring boot中flyway执行源码分析

按照boot的通用习惯,为了引入某个组件的功能,就会在spring.factories引入这个组件的配置类,一般的这个配置类的名称就叫xxxAutoConfiguration,果不其然在spring-boot-autoconfigure 这个jar包的spring.factories文件夹下发现了这样一句

org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration

好,那我们直接的进入这个配置类就可以了,可以看到在boot针对flyway的配置相关的类就9个,如下图
示意图14.png

其中FlywayProperties不用讲,就是我们上一章讲的加载配置信息的bean
主要看下FlywayAutoConfiguration类的相关代码,如下

@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(Flyway.class) 
@Conditional(FlywayDataSourceCondition.class)
@ConditionalOnProperty(prefix = "spring.flyway", name = "enabled", matchIfMissing = true)
@AutoConfigureAfter({ DataSourceAutoConfiguration.class, JdbcTemplateAutoConfiguration.class,
        HibernateJpaAutoConfiguration.class }) 必须DataSource,JdbcTemplate,或是HibernateJpa加载之后
@Import({ FlywayEntityManagerFactoryDependsOnPostProcessor.class, FlywayJdbcOperationsDependsOnPostProcessor.class,
        FlywayNamedParameterJdbcOperationsDependencyConfiguration.class })
public class FlywayAutoConfiguration {

    @Bean
        //自定义的转化器,会将string或是数字转成MigrationVersion
    @ConfigurationPropertiesBinding 
    public StringOrNumberToMigrationVersionConverter stringOrNumberMigrationVersionConverter() {
        return new StringOrNumberToMigrationVersionConverter();
    }

    @Bean
    public FlywaySchemaManagementProvider flywayDefaultDdlModeProvider(ObjectProvider<Flyway> flyways) {
        return new FlywaySchemaManagementProvider(flyways);
    }

    @Configuration(proxyBeanMethods = false)
    @ConditionalOnMissingBean(Flyway.class)
    @EnableConfigurationProperties({ DataSourceProperties.class, FlywayProperties.class })
    @Import({ FlywayMigrationInitializerEntityManagerFactoryDependsOnPostProcessor.class,
            FlywayMigrationInitializerJdbcOperationsDependsOnPostProcessor.class,
            FlywayMigrationInitializerNamedParameterJdbcOperationsDependsOnPostProcessor.class })
    public static class FlywayConfiguration {

        @Bean
        public Flyway flyway(FlywayProperties properties, DataSourceProperties dataSourceProperties,
                ResourceLoader resourceLoader, ObjectProvider<DataSource> dataSource,
                @FlywayDataSource ObjectProvider<DataSource> flywayDataSource,
                ObjectProvider<FlywayConfigurationCustomizer> fluentConfigurationCustomizers,
                ObjectProvider<JavaMigration> javaMigrations, ObjectProvider<Callback> callbacks) {
            FluentConfiguration configuration = new FluentConfiguration(resourceLoader.getClassLoader());
//如果Flyway配置了DataSource信息,就使用,不然使用配置的项目的DataSource信息
            DataSource dataSourceToMigrate = configureDataSource(configuration, properties, dataSourceProperties,
                    flywayDataSource.getIfAvailable(), dataSource.getIfUnique());
            checkLocationExists(dataSourceToMigrate, properties, resourceLoader);
//将properties赋值到configuration
            configureProperties(configuration, properties);
            List<Callback> orderedCallbacks = callbacks.orderedStream().collect(Collectors.toList());
//注册callbacks
            configureCallbacks(configuration, orderedCallbacks);
            fluentConfigurationCustomizers.orderedStream().forEach((customizer) -> customizer.customize(configuration));
            configureFlywayCallbacks(configuration, orderedCallbacks);
            List<JavaMigration> migrations = javaMigrations.stream().collect(Collectors.toList());
//注册JavaMigration,我们基本都是用的sql的写法,这个可以忽略
            configureJavaMigrations(configuration, migrations);
            return configuration.load();
        }

        private DataSource configureDataSource(FluentConfiguration configuration, FlywayProperties properties,
                DataSourceProperties dataSourceProperties, DataSource flywayDataSource, DataSource dataSource) {
            if (properties.isCreateDataSource()) {
                String url = getProperty(properties::getUrl, dataSourceProperties::determineUrl);
                String user = getProperty(properties::getUser, dataSourceProperties::determineUsername);
                String password = getProperty(properties::getPassword, dataSourceProperties::determinePassword);
                configuration.dataSource(url, user, password);
                if (!CollectionUtils.isEmpty(properties.getInitSqls())) {
                    String initSql = StringUtils.collectionToDelimitedString(properties.getInitSqls(), "\n");
                    configuration.initSql(initSql);
                }
            }
            else if (flywayDataSource != null) {
                configuration.dataSource(flywayDataSource);
            }
            else {
                configuration.dataSource(dataSource);
            }
            return configuration.getDataSource();
        }

        private void checkLocationExists(DataSource dataSource, FlywayProperties properties,
                ResourceLoader resourceLoader) {
            if (properties.isCheckLocation()) {
                List<String> locations = new LocationResolver(dataSource).resolveLocations(properties.getLocations());
                if (!hasAtLeastOneLocation(resourceLoader, locations)) {
                    throw new FlywayMigrationScriptMissingException(locations);
                }
            }
        }

        private void configureProperties(FluentConfiguration configuration, FlywayProperties properties) {
            PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull();
            String[] locations = new LocationResolver(configuration.getDataSource())
                    .resolveLocations(properties.getLocations()).toArray(new String[0]);
            map.from(locations).to(configuration::locations);
            map.from(properties.getEncoding()).to(configuration::encoding);
            map.from(properties.getConnectRetries()).to(configuration::connectRetries);
            map.from(properties.getSchemas()).as(StringUtils::toStringArray).to(configuration::schemas);
            map.from(properties.getTable()).to(configuration::table);
            // No method reference for compatibility with Flyway 5.x
            map.from(properties.getTablespace()).whenNonNull().to((tablespace) -> configuration.tablespace(tablespace));
            map.from(properties.getBaselineDescription()).to(configuration::baselineDescription);
            map.from(properties.getBaselineVersion()).to(configuration::baselineVersion);
            map.from(properties.getInstalledBy()).to(configuration::installedBy);
            map.from(properties.getPlaceholders()).to(configuration::placeholders);
            map.from(properties.getPlaceholderPrefix()).to(configuration::placeholderPrefix);
            map.from(properties.getPlaceholderSuffix()).to(configuration::placeholderSuffix);
            map.from(properties.isPlaceholderReplacement()).to(configuration::placeholderReplacement);
            map.from(properties.getSqlMigrationPrefix()).to(configuration::sqlMigrationPrefix);
            map.from(properties.getSqlMigrationSuffixes()).as(StringUtils::toStringArray)
                    .to(configuration::sqlMigrationSuffixes);
            map.from(properties.getSqlMigrationSeparator()).to(configuration::sqlMigrationSeparator);
            map.from(properties.getRepeatableSqlMigrationPrefix()).to(configuration::repeatableSqlMigrationPrefix);
            map.from(properties.getTarget()).to(configuration::target);
            map.from(properties.isBaselineOnMigrate()).to(configuration::baselineOnMigrate);
            map.from(properties.isCleanDisabled()).to(configuration::cleanDisabled);
            map.from(properties.isCleanOnValidationError()).to(configuration::cleanOnValidationError);
            map.from(properties.isGroup()).to(configuration::group);
            map.from(properties.isIgnoreMissingMigrations()).to(configuration::ignoreMissingMigrations);
            map.from(properties.isIgnoreIgnoredMigrations()).to(configuration::ignoreIgnoredMigrations);
            map.from(properties.isIgnorePendingMigrations()).to(configuration::ignorePendingMigrations);
            map.from(properties.isIgnoreFutureMigrations()).to(configuration::ignoreFutureMigrations);
            map.from(properties.isMixed()).to(configuration::mixed);
            map.from(properties.isOutOfOrder()).to(configuration::outOfOrder);
            map.from(properties.isSkipDefaultCallbacks()).to(configuration::skipDefaultCallbacks);
            map.from(properties.isSkipDefaultResolvers()).to(configuration::skipDefaultResolvers);
            map.from(properties.isValidateOnMigrate()).to(configuration::validateOnMigrate);
            // Pro properties
            map.from(properties.getBatch()).whenNonNull().to(configuration::batch);
            map.from(properties.getDryRunOutput()).whenNonNull().to(configuration::dryRunOutput);
            map.from(properties.getErrorOverrides()).whenNonNull().to(configuration::errorOverrides);
            map.from(properties.getLicenseKey()).whenNonNull().to(configuration::licenseKey);
            map.from(properties.getOracleSqlplus()).whenNonNull().to(configuration::oracleSqlplus);
            // No method reference for compatibility with Flyway 5.x
            map.from(properties.getOracleSqlplusWarn()).whenNonNull()
                    .to((oracleSqlplusWarn) -> configuration.oracleSqlplusWarn(oracleSqlplusWarn));
            map.from(properties.getStream()).whenNonNull().to(configuration::stream);
            map.from(properties.getUndoSqlMigrationPrefix()).whenNonNull().to(configuration::undoSqlMigrationPrefix);
        }

        private void configureCallbacks(FluentConfiguration configuration, List<Callback> callbacks) {
            if (!callbacks.isEmpty()) {
                configuration.callbacks(callbacks.toArray(new Callback[0]));
            }
        }

        private void configureFlywayCallbacks(FluentConfiguration flyway, List<Callback> callbacks) {
            if (!callbacks.isEmpty()) {
                flyway.callbacks(callbacks.toArray(new Callback[0]));
            }
        }

        private void configureJavaMigrations(FluentConfiguration flyway, List<JavaMigration> migrations) {
            if (!migrations.isEmpty()) {
                try {
                    flyway.javaMigrations(migrations.toArray(new JavaMigration[0]));
                }
                catch (NoSuchMethodError ex) {
                    // Flyway 5.x
                }
            }
        }

        private String getProperty(Supplier<String> property, Supplier<String> defaultValue) {
            String value = property.get();
            return (value != null) ? value : defaultValue.get();
        }

        private boolean hasAtLeastOneLocation(ResourceLoader resourceLoader, Collection<String> locations) {
            for (String location : locations) {
                if (resourceLoader.getResource(normalizePrefix(location)).exists()) {
                    return true;
                }
            }
            return false;
        }

        private String normalizePrefix(String location) {
            return location.replace("filesystem:", "file:");
        }
                //这个bean很重要,会在下一章讲到
        @Bean
        @ConditionalOnMissingBean
        public FlywayMigrationInitializer flywayInitializer(Flyway flyway,
                ObjectProvider<FlywayMigrationStrategy> migrationStrategy) {
            return new FlywayMigrationInitializer(flyway, migrationStrategy.getIfAvailable());
        }

    }

    /**

     * Post processor to ensure that {@link EntityManagerFactory} beans depend on any
     * {@link FlywayMigrationInitializer} beans.
     */
    @ConditionalOnClass(LocalContainerEntityManagerFactoryBean.class)
    @ConditionalOnBean(AbstractEntityManagerFactoryBean.class)
    static class FlywayMigrationInitializerEntityManagerFactoryDependsOnPostProcessor
            extends EntityManagerFactoryDependsOnPostProcessor {

        FlywayMigrationInitializerEntityManagerFactoryDependsOnPostProcessor() {
            super(FlywayMigrationInitializer.class);
        }

    }

    /**
         *此BeanFactoryPostProcessor保证了JdbcOperations depends on 
          *FlywayMigrationInitializer,如下的两个也是这个意思,保证了在对db做任何的操作前
          *先会完成Flyway的migrate操作
     * Post processor to ensure that {@link JdbcOperations} beans depend on any
     * {@link FlywayMigrationInitializer} beans.
     */
    @ConditionalOnClass(JdbcOperations.class)
    @ConditionalOnBean(JdbcOperations.class)
    static class FlywayMigrationInitializerJdbcOperationsDependsOnPostProcessor
            extends JdbcOperationsDependsOnPostProcessor {

        FlywayMigrationInitializerJdbcOperationsDependsOnPostProcessor() {
            super(FlywayMigrationInitializer.class);
        }

    }

    /**
     * Post processor to ensure that {@link NamedParameterJdbcOperations} beans 
         *depend on
     * any {@link FlywayMigrationInitializer} beans.
     */
    @ConditionalOnClass(NamedParameterJdbcOperations.class)
    @ConditionalOnBean(NamedParameterJdbcOperations.class)
    static class FlywayMigrationInitializerNamedParameterJdbcOperationsDependsOnPostProcessor
            extends NamedParameterJdbcOperationsDependsOnPostProcessor {

        FlywayMigrationInitializerNamedParameterJdbcOperationsDependsOnPostProcessor() {
            super(FlywayMigrationInitializer.class);
        }

    }

    /**
     * Post processor to ensure that {@link EntityManagerFactory} beans depend on any
     * {@link Flyway} beans.
     */
    @ConditionalOnClass(LocalContainerEntityManagerFactoryBean.class)
    @ConditionalOnBean(AbstractEntityManagerFactoryBean.class)
    static class FlywayEntityManagerFactoryDependsOnPostProcessor extends EntityManagerFactoryDependsOnPostProcessor {

        FlywayEntityManagerFactoryDependsOnPostProcessor() {
            super(Flyway.class);
        }

    }

    /**
     * Post processor to ensure that {@link JdbcOperations} beans depend on any
     * {@link Flyway} beans.
     */
    @ConditionalOnClass(JdbcOperations.class)
    @ConditionalOnBean(JdbcOperations.class)
    static class FlywayJdbcOperationsDependsOnPostProcessor extends JdbcOperationsDependsOnPostProcessor {

        FlywayJdbcOperationsDependsOnPostProcessor() {
            super(Flyway.class);
        }

    }

    /**
     * Post processor to ensure that {@link NamedParameterJdbcOperations} beans depend on
     * any {@link Flyway} beans.
     */
    @ConditionalOnClass(NamedParameterJdbcOperations.class)
    @ConditionalOnBean(NamedParameterJdbcOperations.class)
    protected static class FlywayNamedParameterJdbcOperationsDependencyConfiguration
            extends NamedParameterJdbcOperationsDependsOnPostProcessor {

        public FlywayNamedParameterJdbcOperationsDependencyConfiguration() {
            super(Flyway.class);
        }

    }

    private static class LocationResolver {

        private static final String VENDOR_PLACEHOLDER = "{vendor}";

        private final DataSource dataSource;

        LocationResolver(DataSource dataSource) {
            this.dataSource = dataSource;
        }

        List<String> resolveLocations(List<String> locations) {
            if (usesVendorLocation(locations)) {
                DatabaseDriver databaseDriver = getDatabaseDriver();
                return replaceVendorLocations(locations, databaseDriver);
            }
            return locations;
        }

        private List<String> replaceVendorLocations(List<String> locations, DatabaseDriver databaseDriver) {
            if (databaseDriver == DatabaseDriver.UNKNOWN) {
                return locations;
            }
            String vendor = databaseDriver.getId();
            return locations.stream().map((location) -> location.replace(VENDOR_PLACEHOLDER, vendor))
                    .collect(Collectors.toList());
        }

        private DatabaseDriver getDatabaseDriver() {
            try {
                String url = JdbcUtils.extractDatabaseMetaData(this.dataSource, "getURL");
                return DatabaseDriver.fromJdbcUrl(url);
            }
            catch (MetaDataAccessException ex) {
                throw new IllegalStateException(ex);
            }

        }

        private boolean usesVendorLocation(Collection<String> locations) {
            for (String location : locations) {
                if (location.contains(VENDOR_PLACEHOLDER)) {
                    return true;
                }
            }
            return false;
        }

    }

    /**
     * Convert a String or Number to a {@link MigrationVersion}.
     */
    private static class StringOrNumberToMigrationVersionConverter implements GenericConverter {

        private static final Set<ConvertiblePair> CONVERTIBLE_TYPES;

        static {
            Set<ConvertiblePair> types = new HashSet<>(2);
            types.add(new ConvertiblePair(String.class, MigrationVersion.class));
            types.add(new ConvertiblePair(Number.class, MigrationVersion.class));
            CONVERTIBLE_TYPES = Collections.unmodifiableSet(types);
        }

        @Override
        public Set<ConvertiblePair> getConvertibleTypes() {
            return CONVERTIBLE_TYPES;
        }

        @Override
        public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
            String value = ObjectUtils.nullSafeToString(source);
            return MigrationVersion.fromVersion(value);
        }

    }

    static final class FlywayDataSourceCondition extends AnyNestedCondition {

        FlywayDataSourceCondition() {
            super(ConfigurationPhase.REGISTER_BEAN);
        }

        @ConditionalOnBean(DataSource.class)
        private static final class DataSourceBeanCondition {

        }

        @ConditionalOnProperty(prefix = "spring.flyway", name = "url", matchIfMissing = false)
        private static final class FlywayUrlCondition {

        }

    }

}

上面这个configuration主要就是创建了一个叫flyway的bean,并在创建的过程中对配置属性做了check和相关的callback的注册

flyway从入门到精通(八):spring boot中flyway执行源码分析

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,383评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,522评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,852评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,621评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,741评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,929评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,076评论 3 410
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,803评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,265评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,582评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,716评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,395评论 4 333
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,039评论 3 316
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,798评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,027评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,488评论 2 361
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,612评论 2 350