(Spring第二次课)面向切面(JDK 动态代理 spring动态代理)

本文介绍如何使用JDK动态代理及Spring框架实现面向切面编程(AOP),包括创建DAO接口及其实现类,通过代理类拦截方法调用并执行额外操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先写一个dao层
例如是UsersDao

/这个dao是一个接口,创建一个增加的方法,可用于测试即可
public void add(int a,int b);

写一个实现UsersDao类的类UsersDaoImp作为目标对象

//重写UsersDao里面的方法
public void add(int a,int b){
System.out.println(a+b);
}
//写一个(JDK 动态代理)代理类JDKProxy 实现InvocationHandler
//目标对象
private object target;
//代理对象与目标对象糅合进行绑定
public Object bind(Object target){
    this.target=target;
    //返回代理实例
		//参数一:获取目标对象类的加载
		//参数二:获取目标对象类的所有接口
		//参数三:绑定对象
		return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
}

//重写invoke方法
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		System.out.println("之前");
		//执行目标对象的方法
		Object object=method.invoke(target, args);
		System.out.println("之后");
		return object;
	}

//写一个spring 动态代理方式的代理类SpringProxy
//实现MethodInterceptor接口
//方法重写invoke
public Object invoke(MethodInvocation invocation) throws Throwable {
          System.out.println("植入前");
	     Object object=  invocation.proceed();
	     System.out.println("植入后");
		return object;
	}
<!-- 去xml当中配置 -->
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

   <!-- 目标对象 -->
    <bean id="userdsDao" class="com.hlp.dao.imp.UsersDaoImp"></bean>
    
    <!-- 代理对象 -->

    <bean id="springprocy" class="com.hlp.procy.SpringProcy"></bean>
    
    <!-- 新的对象 将目标对象与代理对象糅合在一起 -->
    <bean id="beanproxy" class="org.springframework.aop.framework.ProxyFactoryBean">
    <property name="target" ref="userdsDao"></property>
    <property name="interceptorNames">
    <list>
    <value>springprocy</value>
    </list>
    </property>
    </bean>
</beans>

写一个test测试类

//测试JDK 动态代理方式的面向切面
UsersDao udo=new UsersDaoImp();
JDKProxy proxy=new JDKProxy ();
UsersDao udao2=(UsersDao )proxy.bind(udo);
udao2.add(10,20);

//测试Spring 动态代理方式的面向切面
//创建spring仓库
BeanFactory factory=new XmlBeanFactory(new ClassPathResource("applicationContext.xml"));
		//new ClassPathXmlApplicationContext()
		//获取目标对象
	    UsersDao uDao3=(UsersDao) factory.getBean("beanproxy");
	    //调用里面的方法
	    uDao3.add(10, 20);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值