001/*
002 * Copyright 2012-2018 the original author or authors.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *      http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package org.springframework.boot.autoconfigure.liquibase;
018
019import java.lang.reflect.Method;
020
021import javax.sql.DataSource;
022
023import liquibase.exception.LiquibaseException;
024import liquibase.integration.spring.SpringLiquibase;
025
026import org.springframework.beans.factory.DisposableBean;
027import org.springframework.util.ReflectionUtils;
028
029/**
030 * A custom {@link SpringLiquibase} extension that closes the underlying
031 * {@link DataSource} once the database has been migrated.
032 *
033 * @author Andy Wilkinson
034 * @since 2.0.6
035 */
036public class DataSourceClosingSpringLiquibase extends SpringLiquibase
037                implements DisposableBean {
038
039        private volatile boolean closeDataSourceOnceMigrated = true;
040
041        public void setCloseDataSourceOnceMigrated(boolean closeDataSourceOnceMigrated) {
042                this.closeDataSourceOnceMigrated = closeDataSourceOnceMigrated;
043        }
044
045        @Override
046        public void afterPropertiesSet() throws LiquibaseException {
047                super.afterPropertiesSet();
048                if (this.closeDataSourceOnceMigrated) {
049                        closeDataSource();
050                }
051        }
052
053        private void closeDataSource() {
054                Class<?> dataSourceClass = getDataSource().getClass();
055                Method closeMethod = ReflectionUtils.findMethod(dataSourceClass, "close");
056                if (closeMethod != null) {
057                        ReflectionUtils.invokeMethod(closeMethod, getDataSource());
058                }
059        }
060
061        @Override
062        public void destroy() throws Exception {
063                if (!this.closeDataSourceOnceMigrated) {
064                        closeDataSource();
065                }
066        }
067
068}