001/* 002 * Copyright 2012-2016 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.context.annotation.Bean; 024import org.springframework.context.annotation.Configuration; 025import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase; 026import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; 027 028/** 029 * Configuration for embedded data sources. 030 * 031 * @author Phillip Webb 032 * @author Stephane Nicoll 033 * @see DataSourceAutoConfiguration 034 */ 035@Configuration 036@EnableConfigurationProperties(DataSourceProperties.class) 037public class EmbeddedDataSourceConfiguration implements BeanClassLoaderAware { 038 039 private EmbeddedDatabase database; 040 041 private ClassLoader classLoader; 042 043 private final DataSourceProperties properties; 044 045 public EmbeddedDataSourceConfiguration(DataSourceProperties properties) { 046 this.properties = properties; 047 } 048 049 @Override 050 public void setBeanClassLoader(ClassLoader classLoader) { 051 this.classLoader = classLoader; 052 } 053 054 @Bean 055 public EmbeddedDatabase dataSource() { 056 EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder() 057 .setType(EmbeddedDatabaseConnection.get(this.classLoader).getType()); 058 this.database = builder.setName(this.properties.getName()) 059 .generateUniqueName(this.properties.isGenerateUniqueName()).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}