码迷,mamicode.com
首页 > 数据库 > 详细

自定义java注解(二) 实现DBHelper中的getCon( )得到数据库连接

时间:2015-08-08 00:05:04      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:数据库   annotion   自定义注解   

  1. 定义一个DBinfo 注解
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Inherited
public @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( )得到数据库连接

标签:数据库   annotion   自定义注解   

原文地址:http://blog.csdn.net/emilyrr/article/details/47345777

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!