來項目內用的是普通資料來源.考慮沒有分布式的資料訪問.就使用了apache-commons-dbcp.但是後來項目內要加一個第三方的報表製作工具.該工具強制要求使用JNDI來獲得串連(該死的)沒辦法.只有加了.顯將配置步驟和一個錯誤做筆記如下:
1. 環境: windowsXp系統.使用的是jbossGA-4.2.2 sqlserver2000.
項目架構是 Spring+ibatis+struts.
2. 配置步驟1 . 由於jboss會自動尋找server\default\deploy目錄下的 **-ds.xml檔案.並讀取其中內容.來得到相應的DataSource,我的檔案具體內容如下:
<?xml version="1.0" encoding="UTF-8"?>
<datasources>
<local-tx-datasource>
<jndi-name>jdbc/DataSource</jndi-name>
<connection-url>jdbc:jtds:sqlserver://localhost:1433/fnx</connection-url>
<driver-class>net.sourceforge.jtds.jdbc.Driver</driver-class>
<user-name>sa</user-name>
<password>1234</password>
<metadata>
<type-mapping>MS SQLSERVER2000</type-mapping>
</metadata>
</local-tx-datasource>
</datasources>
配置步驟2 . (有部分內容來自網上) 由於使用spring來擷取jndi.所以實現了FactoryBean, InitializingBean
get/set方法沒加
public class DataSourceFactoryBean implements FactoryBean, InitializingBean {
/** 快取資料來源物件 */
private DataSource dataSource;
/** 是否jndi資料來源 */
private boolean jndi;
/** 資料來源的名字(如果是jndi資料來源) */
private String jndiName;
/** jdbc驅動類(非jndi的情況) */
private String driverClassName;
/** 資料庫的url(非jndi的情況) */
private String url;
/** 使用者名稱(非jndi的情況) */
private String username;
/** 密碼(非jndi的情況) */
private String password;
public void afterPropertiesSet() throws Exception {
if (this.isJndi()) {
if (!org.springframework.util.StringUtils.hasText(this.jndiName)) {
throw new IllegalArgumentException("jndiName is required");
}
} else {
if (!org.springframework.util.StringUtils
.hasText(this.driverClassName)) {
throw new IllegalArgumentException(
"driverClassName is required");
}
if (!org.springframework.util.StringUtils.hasText(this.url)) {
throw new IllegalArgumentException("url is required");
}
if (!org.springframework.util.StringUtils.hasText(this.username)) {
throw new IllegalArgumentException("username is required");
}
if (!org.springframework.util.StringUtils.hasText(this.password)) {
throw new IllegalArgumentException("password is required");
}
}
// 在初始化時就建立資料來源
this.createDataSource();
}
public Object getObject() throws Exception {
DataSource ds = this.createDataSource();
return ds;
}
public Class getObjectType() {
return javax.sql.DataSource.class;
}
public boolean isSingleton() {
return true;
}
protected DataSource createDataSource() {
DataSource ds = this.dataSource;
if (ds == null) {
try {
if (this.isJndi()) {
ds = new JndiDataSourceSupport()
.lookupDataSource(this.jndiName);
} else {
ds = new DriverManagerDataSource(driverClassName, url,
username, password);
}
} catch (Throwable err) {
throw new RuntimeException(err);
}
}
this.dataSource = ds;
return ds;
}
private class JndiDataSourceSupport extends JndiLocatorSupport {
public DataSource lookupDataSource(String jndiName)
throws NamingException {
return (DataSource) super.lookup(jndiName,getObjectType());
}
}
}