通过反射获取DataSource里数据源的账号密码

public Connection getDbConnection()
    {
        Connection conn = null;
        // 获得连接
        DataSource ds = null;
        try
        {
            Context ctx = new InitialContext();
            ds = (DataSource) ctx.lookup("java:comp/env/PCMSDB");
           //ds = (DataSource) ctx.lookup("PCMSJN");// weblogic环境配置数据源
            Class c = ds.getClass();
            //Object invokeTest = c.newInstance();
            Method getPassword = c.getMethod("getPassword", null);
            Method getUsername = c.getMethod("getUsername", null);
            
            Object pwd = getPassword.invoke(ds, null);
            Object username = getUsername.invoke(ds, null);
            //测试输出
            System.out.println("getDbConnection pwd:"+pwd.toString());
            System.out.println("getDbConnection username:"+username.toString());
        }
        catch (Exception e)
        {
            System.out.println("getDbConnection Exception "+e.getMessage());
            e.printStackTrace();
        }
        try
        {
            conn = ds.getConnection();
        }
        catch (SQLException e)        
        {            
            System.out.println("getDbConnection SQLException "+e.getMessage());
        }
        return conn;

    }

 

posted @ 2018-10-30 12:02  小泉哥  阅读(2544)  评论(0编辑  收藏  举报