动态代理的过程
1、编写代理接口
public interface Sale {
void chuzu(int yuan);
void eat();
}
2、编写真实对象
public class FangDong implements Sale{
@Override
public void chuzu(int yuan) {
System.out.println("房东收到的金额:"+yuan);
}
@Override
public void eat() {
System.out.println("我要吃饭了");
}
}
3、使用Proxy.newProxyInstance()获得代理对象
public class Main {
public static void main(String[] args) {
FangDong fangDong = new FangDong();
Sale proxy = (Sale) Proxy.newProxyInstance(
fangDong.getClass().getClassLoader(),
fangDong.getClass().getInterfaces(),
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("我是代理对象,我开始工作了");
Object res=null;
if(method.getName().equals("chuzu")){
int y= (int) ((int)args[0]*0.2);
System.out.println("中介收小费:"+y);
args[0] = (int) args[0] - y;
}
res=method.invoke(fangDong,args);
return res;
}
});
proxy.chuzu(2000);
proxy.eat();
}
}
spring AOP的两种实现方式
1、配置xml文件开启AOP
- 先编写切入后所需要执行的方法
public class LogClass {
public void before(){
System.out.println("前置增强");
}
public void after(){
System.out.println("后置增强");
}
}
- 在xml进行配置,开启AOP
<bean id="log" class="com.qst.log.LogClass"/>
<aop:config>
<aop:aspect ref="log">
<aop:pointcut id="logPointcut" expression="execution(* com.qst.pojo.*.eat(..))"/>
<aop:after method="after" pointcut-ref="logPointcut"/>
<aop:before method="before" pointcut-ref="logPointcut"/>
</aop:aspect>
</aop:config>
2、注解实现AOP
- 编写增强类,加上注解
@Aspect
public class LogClass {
@Pointcut("execution(* com.qst.pojo.*.*(..))")
public void myPointcut(){}
@Around("myPointcut()")
public void around(ProceedingJoinPoint pjt){
try {
System.out.println("前置增强");
pjt.proceed();
System.out.println("后置增强");
} catch (Throwable throwable) {
throwable.printStackTrace();
System.out.println("异常增强");
} finally {
System.out.println("最终增强");
}
}
}
- 在xml文件中开启注解支持
<bean id="log" class="com.qst.log.LogClass"/>
<aop:aspectj-autoproxy/>
JDK动态代理和CGLIB动态代理的区别
- JDK动态代理值提供了接口的代理,不支持类的代理;
- spring AOP 进行代理时若代理的对象没有实现接口,则会使用CGLIB动态代理进行处理,CGLIB在运行时动态的生成目标类的一个子类。并且会重写父类所有的方法增强代码,调用时先通过代理类进行增强,再直接调用父类对应的方法进行调用目标方法。从而实现AOP。