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);
        }
  • 相关阅读:
    C语言枚举类型(C语言enum用法)详解
    基础练习 报时助手
    怎么将CAD转JPG?教你两种CAD转JPG方法
    CAD图纸怎么看?这两种方法值得看
    某酒店建筑设计CAD施工图
    CAD怎么算面积?这种方法你要知道
    怎么将DWG转PDF?分享一个在线转换方法
    如何使用CAD删除命令?怎么删除图纸中线段
    CAD制图软件哪个好?试试这两个就知道了
    CAD制图初学入门如何学好CAD?CAD大神总结5点诀窍,必须收藏
  • 原文地址:https://www.cnblogs.com/freemanabc/p/5460688.html
Copyright © 2011-2022 走看看