自訂java註解(二) 實現DBHelper中的getCon( )得到資料庫連接

來源:互聯網
上載者:User

標籤:資料庫   annotion   自訂註解   

  1. 定義一個DBinfo 註解
@Documented@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.METHOD)@Inheritedpublic @interface DBinfo {    public String URL() ;    public String Username() ;    public String Password() ;    public String Driver() ;}
  1. 建立DBHelper,實現 getCon方法 注意導包
public class DBHelper {    @DBinfo(URL="jdbc:mysql://localhost:3306/test",Username="root",Password="Rindy_RR",Driver="com.mysql.jdbc.Driver")    public Connection getCon(String URL,String Username,String Password,String Driver){        Connection con=null;        try{            Class.forName(Driver).newInstance();            con=DriverManager.getConnection(URL,Username,Password);        } catch (Exception e) {            throw new RuntimeException(e);        }        //直接在控制台輸出,看con是否成功得到        System.out.println(con.toString());        return con;    }}
  1. 解析架構的實現
public class ParseDBinfo {    public void parseMethod(Class clazz) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException{        Object obj = clazz.newInstance();        Method[] methods=clazz.getDeclaredMethods();        for(Method m:methods){            DBinfo dbinfo=m.getAnnotation(DBinfo.class);            if(dbinfo!=null){                String URL=dbinfo.URL();                String Username=dbinfo.Username();                String Password=dbinfo.Password();                String Driver=dbinfo.Driver();                //容錯處理                if(URL!=null && Username!=null && Password!=null && Driver!=null && !URL.equals("") && !Username.equals("") && !Password.equals("") && !Driver.equals("")){                    m.invoke(obj, URL,Username,Password,Driver);                }else{                    System.out.println("參數不可為空!");                }            }        } }}
  1. 測試類別
public void testApp() throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {        ParseDBinfo pb=new ParseDBinfo();        pb.parseMethod(DBHelper.class);    }

測試結果:

注意getCon( ) 的參數不要寫錯了,根據自己實際的mysql配置來,其實多寫幾次,還是很好理解的。下一次,自訂個Junit,@Test @Before @After

著作權聲明:本文為博主原創文章,謝謝參考!有問題的地方,歡迎糾正,一起進步。

自訂java註解(二) 實現DBHelper中的getCon( )得到資料庫連接

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.