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

来源:互联网 发布:mac连上wifi打不开网页 编辑:程序博客网 时间:2024/04/27 22:06
  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

1 0
原创粉丝点击