在开发业务时,可能核心的业务会经常进行修改,对与重复的代码块,我们可能会把它 单独的提出然后对他进行分装!,然后在需要使用这个模块时再对他进行调,就可以了,我们现在希望实现程序不用主动的调用模块, 而是让系统“自动的执行该特殊的方法“,要想实现这个特殊的方法,我们可以使用AOP,来实现它。
AOP
为什么要使用AOP?
因为随着应用软件的需求不断的增大,传统的oop(面向对象)无法满足需要,oop的弊端明显!AOP与oop互补!
AOP是什么?
AOP 专门用于处理系统中分布于各个模块中交叉关注的问题
AOP的作用是?
AOP 将业务逻辑的各个部分进行隔离,使 开发人员在编写业务逻辑时可以专心于核心的业务,从而提高开发的效率。
代码测试:
1:接口的创建
package com.AopTest;
public interface CustomerDao {
void add();
void update();
void delete();
void find();
}
2:接口的实现(这个可以看做是重复的核心代码块)
package com.AopTest;
public class CustomeDaoImpl implements CustomerDao{
public void add(){
System.out.println("添加");
}
public void update(){
System.out.println("更新");
}public void delete(){
System.out.println("删除");
}public void find(){
System.out.println("查找");
}
}
3:切面类*( 新增加的功能,事务,日志等;把要加入的功能封装成类即可)
package com.AopTest;
public class MyAspect {
public void myBefore() {
System.out.println("方法之前");
}
public void myAfter() {
System.out.println("方法之后");
}
}
4:创建代理类:(实现把切面类注入到程序中)
package com.AopTest;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class MyBeanFactory {
public static CustomerDao getBean() {
final CustomerDao customerDao = new CustomeDaoImpl();
final MyAspect myAspect = new MyAspect();
return (CustomerDao) Proxy.newProxyInstance(MyBeanFactory.class.getClassLoader(),
new Class[] { CustomerDao.class }, new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// TODO 自动生成的方法存根
myAspect.myBefore();
Object obj = method.invoke(customerDao, args);
myAspect.myAfter();
return obj;
}
});
}
}
5:测试类(验证我们的核心代码块是否注入了切面类)
package com.AopTest;
public class JDKProxyTest {
public static void main(String[] args) {
CustomerDao customerDao = MyBeanFactory.getBean();
customerDao.add();
customerDao.update();
customerDao.delete();
customerDao.find();
}
}
6:运行的结果:
6:心得体会
AOP通过使用代理类,把切面类加入到程序中,而不是程序主动调用分装好了的类,而是通过代理类,实现了让系统“自动的执行该特殊的方法“。
在不改变测试类的代码的情况下,通过代理类实现注入切面类,从而在 神不知鬼不觉的情况下实现了改变测试类的结果。