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

  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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值