jdk动态代理强化篇

多说无益,直接上代码:

首先重写InvocationHandler类:
public class MapperProxyInvocationHandler implements InvocationHandler{
    
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //这里写主要的功能强化逻辑与调用业务方法
        //其中Method method代表传过来的业务方法,而Object[] args代表传过来的参数,可以用args[n]来调用参数
        Object obj = method.invoke(delegate,args);	//此处是调用业务方法,而Object obj是方法返回值
        return obj;
    }
}
业务接口:
public interface UserMapper {

    User selectById(int id);
}
业务接口实现类:
public interface UserMapperImpl {

    User selectById(int id){
        
        return new User();
    }
}
测试类:
public class test{
    public static void main(String[] args){
        //先获取需要代理的目标类
		UserMapper userMapper = new UserMapperImpl();
		//Proxy.newProxyInstance()方法可以得到一个代理类对象
		userMapper = (UserMapper) Proxy.newProxyInstance(
            							userMapper.getClass().getClassLoader(),
                                        userMapper.getClass().getInterfaces(),
        								new MapperProxyInvocationHandler());
        
        userMapper.selectById(1);
    }
}

如果我没有业务方法的实现类也可以:

首先重写InvocationHandler类:
public class MapperProxyInvocationHandler implements InvocationHandler{
    
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        
        //一下是对数据库的操作
        String driver = "com.mysql.cj.jdbc.Driver";
        String url = "jdbc:mysql://127.0.0.1:3306/?serverTimezone=UTC&useSSL=false&allowPublicKeyRetrieval=true&useUnicode=true&characterEncoding=utf-8";
        String username = "";
        String password = "";

        String sql = "select * from user where id="+args[0];
        System.out.println(sql);

        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        User user = new User();


        try {
            Class.forName(driver);
            connection = DriverManager.getConnection(url,username,password);
            statement = connection.prepareStatement(sql);
            resultSet = statement.executeQuery();
            if (resultSet.next()){

                user.setId(Integer.parseInt(resultSet.getString("id")));
                user.setName(resultSet.getString("name"));
                user.setAge(Integer.parseInt(resultSet.getString("age")));
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (resultSet != null){
                try {
                    resultSet.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (statement != null){
                try {
                    statement.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (connection != null){
                try {
                    connection.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }

        //这里把查到的数据封装成User对象返回回去
        return user;
    }
}
业务接口:
public interface UserMapper {

    User selectById(int id);
}
测试类:
public class test {

    public static void main(String[] args) {

        UserMapper userMapper = (UserMapper) Proxy.newProxyInstance(
            								//这里直接把接口的ClassLoader返回回去
            								UserMapper.class.getClassLoader(),
            								//这里本来是返回业务接口实现类所实现的业务接口,由于现在这里就是接口,直接返												回去就行了
                							new Class[]{UserMapper.class},
                							new MapperProxyInvocationHandler());
        System.out.println(userMapper.selectById(1));
    }
}

这里用jdk动态代理封装了一个jdbc的查询单条记录功能。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值