1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package com.github.springtestdbunit.bean;
18
19 import javax.sql.DataSource;
20
21 import org.dbunit.database.DatabaseDataSourceConnection;
22 import org.dbunit.database.IDatabaseConnection;
23 import org.springframework.beans.factory.FactoryBean;
24 import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy;
25 import org.springframework.transaction.PlatformTransactionManager;
26 import org.springframework.util.Assert;
27
28
29
30
31
32
33
34
35 public class DatabaseDataSourceConnectionFactoryBean implements FactoryBean<DatabaseDataSourceConnection> {
36
37 private DataSource dataSource;
38
39 private boolean transactionAware = true;
40
41 private String username;
42
43 private String password;
44
45 private String schema;
46
47 private DatabaseConfigBean databaseConfig;
48
49 public DatabaseDataSourceConnectionFactoryBean() {
50 super();
51 }
52
53 public DatabaseDataSourceConnectionFactoryBean(DataSource dataSource) {
54 super();
55 this.dataSource = dataSource;
56 }
57
58 public DatabaseDataSourceConnection getObject() throws Exception {
59 Assert.notNull(this.dataSource, "The dataSource is required");
60 DatabaseDataSourceConnection dataSourceConnection = new DatabaseDataSourceConnection(
61 makeTransactionAware(this.dataSource), this.schema, this.username, this.password);
62 if (this.databaseConfig != null) {
63 this.databaseConfig.apply(dataSourceConnection.getConfig());
64 }
65 return dataSourceConnection;
66 }
67
68 private DataSource makeTransactionAware(DataSource dataSource) {
69 if ((dataSource instanceof TransactionAwareDataSourceProxy) || !this.transactionAware) {
70 return dataSource;
71 }
72 return new TransactionAwareDataSourceProxy(dataSource);
73 }
74
75 public Class<?> getObjectType() {
76 return DatabaseDataSourceConnection.class;
77 }
78
79 public boolean isSingleton() {
80 return true;
81 }
82
83
84
85
86
87
88 public void setDataSource(DataSource dataSource) {
89 Assert.notNull(dataSource, "The dataSource is required.");
90 this.dataSource = dataSource;
91 }
92
93
94
95
96
97 public void setUsername(String username) {
98 this.username = username;
99 }
100
101
102
103
104
105 public void setPassword(String password) {
106 this.password = password;
107 }
108
109
110
111
112
113 public void setSchema(String schema) {
114 this.schema = schema;
115 }
116
117
118
119
120
121
122
123 public void setDatabaseConfig(DatabaseConfigBean databaseConfig) {
124 this.databaseConfig = databaseConfig;
125 }
126
127
128
129
130
131
132 public void setTransactionAware(boolean transactionAware) {
133 this.transactionAware = transactionAware;
134 }
135
136
137
138
139
140
141
142 public static IDatabaseConnection newConnection(DataSource dataSource) {
143 try {
144 return (new DatabaseDataSourceConnectionFactoryBean(dataSource)).getObject();
145 } catch (Exception ex) {
146 throw new IllegalStateException(ex);
147 }
148 }
149
150 }