為了統一生產環境與本地開發的數據源訪問方式,將數據源配置為 JNDI 形式。本文記錄 Jetty Maven Plugin 整合 C3P0 JNDI 數據源的完整步驟。
項目根目錄或 src/main/resources 下新建 jetty.xml:
<Configure id="Server" class="org.eclipse.jetty.server.Server">
<New id="scmsDs" class="org.eclipse.jetty.plus.jndi.Resource">
<Arg></Arg> <!-- 空作用域,綁定到 java:comp/env -->
<Arg>java:scmsDS</Arg> <!-- JNDI 名稱 -->
<Arg>
<New class="com.mchange.v2.c3p0.ComboPooledDataSource">
<Set name="driverClass">${jdbc.driverClassName}</Set>
<Set name="jdbcUrl">${jdbc.url}</Set>
<Set name="user">${jdbc.username}</Set>
<Set name="password">${jdbc.password}</Set>
</New>
</Arg>
</New>
</Configure>
<New> 定義多個數據源${...} 占位符,配合 Maven 資源過濾或系統屬性注入<plugin>
<groupId>org.mortbay.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>8.1.2.v20120308</version>
<dependencies>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<dependency>
<groupId>com.oracle.jdbc</groupId>
<artifactId>ojdbc5</artifactId>
<version>11.2.0.3</version>
</dependency>
</dependencies>
<configuration>
<jettyXml>${project.build.outputDirectory}/jetty.xml</jettyXml>
</configuration>
</plugin>
關鍵點:Plugin 依賴中必須聲明 C3P0 及 JDBC 驅動,否則 Jetty ClassLoader 找不到類。
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:scmsDS" />
<property name="resourceRef" value="true" /> <!-- 自動補全 java:comp/env/ -->
</bean>
後續 DAO/Service 正常注入 dataSource,無感知切換。
mvn jetty:run 啟動NameNotFoundException| 現象 | 原因 | 解決 |
|---|---|---|
| javax.naming.NameNotFoundException | JNDI 名稱不匹配 / jetty.xml 未加載 | 檢查 jettyXml 路徑、JNDI 名稱一致性、web.xml resource-ref |
| ClassNotFoundException: ComboPooledDataSource | Plugin 依賴缺少 c3p0 | 在 plugin/dependencies 添加 c3p0 坐標 |
| Oracle 驅動找不到 | ojdbc 不在中央倉庫 | 手動 install 到本地倉庫或使用私服 |