001/*
002 * Copyright 2012-2017 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 *      https://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 */
016package org.springframework.batch.sample.config;
017
018import javax.annotation.PostConstruct;
019import javax.sql.DataSource;
020
021import org.apache.commons.dbcp2.BasicDataSource;
022
023import org.springframework.beans.factory.annotation.Autowired;
024import org.springframework.context.annotation.Bean;
025import org.springframework.context.annotation.Configuration;
026import org.springframework.context.annotation.PropertySource;
027import org.springframework.core.env.Environment;
028import org.springframework.core.io.ResourceLoader;
029import org.springframework.jdbc.datasource.init.DatabasePopulatorUtils;
030import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;
031
032/**
033 * @author Dave Syer
034 *
035 */
036@Configuration
037@PropertySource("classpath:/batch-hsql.properties")
038public class DataSourceConfiguration {
039        
040        @Autowired
041        private Environment environment;
042        
043        @Autowired
044        private ResourceLoader resourceLoader;
045        
046        @PostConstruct
047        protected void initialize() {
048                ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
049                populator.addScript(resourceLoader.getResource(environment.getProperty("batch.schema.script")));
050                populator.setContinueOnError(true);
051                DatabasePopulatorUtils.execute(populator , dataSource());
052        }
053        
054        @Bean(destroyMethod="close")
055        public DataSource dataSource() {
056                BasicDataSource dataSource = new BasicDataSource();
057                dataSource.setDriverClassName(environment.getProperty("batch.jdbc.driver"));
058                dataSource.setUrl(environment.getProperty("batch.jdbc.url"));
059                dataSource.setUsername(environment.getProperty("batch.jdbc.user"));
060                dataSource.setPassword(environment.getProperty("batch.jdbc.password"));
061                return dataSource;
062        }
063
064}