View Javadoc

1   /*
2    * Copyright 2012-2013 the original author or authors.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package org.springframework.batch.sample.config;
17  
18  import javax.annotation.PostConstruct;
19  import javax.sql.DataSource;
20  
21  import org.apache.commons.dbcp.BasicDataSource;
22  import org.springframework.beans.factory.annotation.Autowired;
23  import org.springframework.context.annotation.Bean;
24  import org.springframework.context.annotation.Configuration;
25  import org.springframework.context.annotation.PropertySource;
26  import org.springframework.core.env.Environment;
27  import org.springframework.core.io.ResourceLoader;
28  import org.springframework.jdbc.datasource.init.DatabasePopulatorUtils;
29  import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;
30  
31  /**
32   * @author Dave Syer
33   *
34   */
35  @Configuration
36  @PropertySource("classpath:/batch-hsql.properties")
37  public class DataSourceConfiguration {
38  	
39  	@Autowired
40  	private Environment environment;
41  	
42  	@Autowired
43  	private ResourceLoader resourceLoader;
44  	
45  	@PostConstruct
46  	protected void initialize() {
47  		ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
48  		populator.addScript(resourceLoader.getResource(environment.getProperty("batch.schema.script")));
49  		populator.setContinueOnError(true);
50  		DatabasePopulatorUtils.execute(populator , dataSource());
51  	}
52  	
53  	@Bean(destroyMethod="close")
54  	public DataSource dataSource() {
55  		BasicDataSource dataSource = new BasicDataSource();
56  		dataSource.setDriverClassName(environment.getProperty("batch.jdbc.driver"));
57  		dataSource.setUrl(environment.getProperty("batch.jdbc.url"));
58  		dataSource.setUsername(environment.getProperty("batch.jdbc.user"));
59  		dataSource.setPassword(environment.getProperty("batch.jdbc.password"));
60  		return dataSource;
61  	}
62  
63  }