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.jdbc;
018
019import javax.annotation.PreDestroy;
020
021import org.springframework.beans.factory.BeanClassLoaderAware;
022import org.springframework.boot.context.properties.EnableConfigurationProperties;
023import org.springframework.boot.jdbc.EmbeddedDatabaseConnection;
024import org.springframework.context.annotation.Bean;
025import org.springframework.context.annotation.Configuration;
026import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase;
027import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
028
029/**
030 * Configuration for embedded data sources.
031 *
032 * @author Phillip Webb
033 * @author Stephane Nicoll
034 * @see DataSourceAutoConfiguration
035 */
036@Configuration
037@EnableConfigurationProperties(DataSourceProperties.class)
038public class EmbeddedDataSourceConfiguration implements BeanClassLoaderAware {
039
040        private EmbeddedDatabase database;
041
042        private ClassLoader classLoader;
043
044        private final DataSourceProperties properties;
045
046        public EmbeddedDataSourceConfiguration(DataSourceProperties properties) {
047                this.properties = properties;
048        }
049
050        @Override
051        public void setBeanClassLoader(ClassLoader classLoader) {
052                this.classLoader = classLoader;
053        }
054
055        @Bean
056        public EmbeddedDatabase dataSource() {
057                this.database = new EmbeddedDatabaseBuilder()
058                                .setType(EmbeddedDatabaseConnection.get(this.classLoader).getType())
059                                .setName(this.properties.determineDatabaseName()).build();
060                return this.database;
061        }
062
063        @PreDestroy
064        public void close() {
065                if (this.database != null) {
066                        this.database.shutdown();
067                }
068        }
069
070}