zoukankan      html  css  js  c++  java
  • 读取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);
        }
  • 相关阅读:
    bash 中 () {} [] [[]] (()) 的解释
    正则表达式速查笔记
    Makefile速查笔记
    gflags 编译动态库
    在Win10上运行ESXI-Comstomer
    GNU g++常用编译选项用法
    C++标准转换运算符reinterpret_cast
    BZOJ 3211: 花神游历各国【线段树区间开方问题】
    BZOJ 1597: [Usaco2008 Mar]土地购买【斜率优化+凸包维护】
    BZOJ 1046: [HAOI2007]上升序列【贪心+二分状态+dp+递归】
  • 原文地址:https://www.cnblogs.com/freemanabc/p/5460688.html
Copyright © 2011-2022 走看看