View Javadoc

1   /*
2    * Copyright 2002-2006 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  
17  package org.springbyexample.jdbc.datasource;
18  
19  import java.sql.Driver;
20  
21  import org.springbyexample.jdbc.core.SqlScriptProcessor;
22  import org.springframework.beans.factory.InitializingBean;
23  import org.springframework.jdbc.datasource.SimpleDriverDataSource;
24  import org.springframework.util.Assert;
25  import org.springframework.util.ClassUtils;
26  import org.springframework.util.StringUtils;
27  
28  
29  /**
30   * Initializing version of <code>DriverManagerDataSource</code>.
31   * After the properties are set any database initialization scripts are run.
32   * This is very useful for unit testing.
33   * 
34   * @author David Winterfeldt
35   * 
36   * @see org.springframework.jdbc.datasource.SimpleDriverDataSource
37   * @see org.springbyexample.jdbc.core.SqlScriptProcessor
38   */
39  public class InitializingDriverManagerDataSource extends SimpleDriverDataSource 
40          implements InitializingBean {
41  
42      protected String driverClassName = null;
43      protected SqlScriptProcessor sqlScriptProcessor = null;
44  
45      /**
46       * Sets driver class name.  The class should implement 
47       * <code>java.sql.Driver</code>.  This is a shortcut for 
48       * calling <code>setDriver(Driver driver)</code> on the parent class.
49       */
50      public void setDriverClassName(String driverClassName) {
51          this.driverClassName = driverClassName;
52      }
53  
54      /**
55       * Sets SQL script processor.
56       */
57      public void setSqlScriptProcessor(SqlScriptProcessor sqlScriptProcessor) {
58          this.sqlScriptProcessor = sqlScriptProcessor;
59      }
60  
61      /**
62       * Implementation of <code>InitializingBean</code>
63       */
64      public void afterPropertiesSet() throws Exception {
65          // if driver class name isn't blank, set 
66          // driver class on SimpleDriverDataSource.
67          if (getDriver() == null && StringUtils.hasText(driverClassName)) {
68              setDriverClass(ClassUtils.forName(driverClassName));
69          }
70          
71          if (sqlScriptProcessor != null) {
72              sqlScriptProcessor.setDataSource(this);
73  
74              sqlScriptProcessor.process();
75          }
76      }
77  
78  }