首先写一个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);