读取WEB-INF目录下的ApplicationContext.xml获取Connection连接
1.获取配置文件路径。
public class CloudClient { /** * */ private static final long serialVersionUID = 5373577151116649741L; public static void main(String ags[]) { try { // 读取WEB-INF下的配置文件 String path = CloudClient.class.getResource("/").getPath(); System.out.println("路径1:" + path);// 路径1:/C:/GenesisTools2011/workspace/SAMS/SAMS/WEB-INF/classes/ String pathA = path.replace("/classes", ""); System.out.println("路径2:" + pathA);// 路径2:/C:/GenesisTools2011/workspace/SAMS/SAMS/WEB-INF/ String pathB = pathA + "/conf/applicationContext/applicationContext.xml"; SpringContext.setApplicationContext(pathB);//加载配置文件
Connection con=getConnection();//获取连接
//... //CloudClient cc = new CloudClient(); // cc.sendMessageToCloud(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
2、SpringContext加载配置文件
public static void setApplicationContext(String path) { ApplicationContext ac = new FileSystemXmlApplicationContext(path); springContext = ac; }
提供getBean方法
public static Object getBean(String key) { return springContext.getBean(key); }
3.传入dataSource数据源配置名称,获取connection连接。
ApplicationContext.xml
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" /> <property name="url" value="jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=10.10.10.10)(PORT=1521)))(CONNECT_DATA=(SERVICE_NAME=orcl)(SERVER=DEDICATED)))" /> <property name="username" value="sams" /> <property name="password" value="abcd1234" />
public static Connection getConnection() { if (dataSource == null) { dataSource = (DataSource) SpringContext.getBean("dataSource"); } return DataSourceUtils.getConnection(dataSource); }