当前位置: 移动技术网 > IT编程>开发语言>Java > AOP简介

AOP简介

2020年07月17日  | 移动技术网IT编程  | 我要评论

标题什么是 AOP

AOP 为 Aspect Oriented Programming 的缩写,意思为面向切面编程,是通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。

AOP 是 OOP 的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。

AOP 的作用及其优势

作用:在程序运行期间,在不修改源码的情况下对方法进行功能增强
优势:减少重复代码,提高开发效率,并且便于维护

AOP 的底层实现

实际上,AOP 的底层是通过 Spring 提供的的动态代理技术实现的。在运行期间,Spring通过动态代理技术动态的生成代理对象,代理对象方法执行时进行增强功能的介入,在去调用目标对象的方法,从而完成功能的增强。

常用的动态代理技术:

  • JDK 代理 : 基于接口的动态代理技术
  • cglib 代理:基于父类的动态代理技术

JDK 的动态代理

1.目标类接口
public interface TargetInterface {
    public void save();
}
2.目标类
public class Target implements TargetInterface {
    public void save() {
        System.out.println("save running.......");
    }
}
3.增强类
public class Advice {
    public void before(){
        System.out.println("前置增强。。。");

    }
    public void after(){
        System.out.println("后置增强。。。");

    }
}

4.动态代理代码
public class ProxyTest {

    public static void main(String[] args) {
       //目标对象
        final Target target=new Target();

      //增强对象
        final Advice advice=new Advice();
        //返回值 就是动态生成的代理对象
        TargetInterface proxy=(TargetInterface) Proxy.newProxyInstance(
                target.getClass().getClassLoader(), //目标对象类加载器
                target.getClass().getInterfaces(),//目标对象相同的接口字节码对象数组
                new InvocationHandler() {
                    //调用代理对象的任何方法 实质执行的都是invoke方法
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        advice.before(); //前置增强
                        Object invoke = method.invoke(target, args);//执行目标方法
                        advice.after();//后置增强
                        return  invoke;
                    }
                }
        );

          //调用代理对象的方法
      proxy.save();
    }
}

cglib 的动态代理

1.目标类

public class Target {
    public void save() {
        System.out.println("save running.......");
    }
}
2.增强类
public class Advice {
    public void before(){
        System.out.println("前置增强。。。");

    }
    public void after(){
        System.out.println("后置增强。。。");

    }
}
3.动态代理代码
public class ProxyTest {

    public static void main(String[] args) {
        //目标对象
        final Target target = new Target();

        //增强对象
        final Advice advice = new Advice();
        //返回值 就是动态生成的代理对象  基于cglib
        //1.创建增强器
        Enhancer enhancer = new Enhancer();
        //2.设置父类(目标)
        enhancer.setSuperclass(Target.class);
        //3.设置回调
        enhancer.setCallback(new MethodInterceptor() {
            public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
                advice.before();               //执行前置
                Object invoke = method.invoke(target, args);//执行目标

                advice.after();//执行后置
                return invoke;
            }
        });
        //4.创建代理对象
             Target proxy= (Target) enhancer.create();

             proxy.save();
    }
}

基于 XML 的 AOP 开发

  1. 导入 AOP 相关坐标
  2. 创建目标接口和目标类(内部有切点)
  3. 创建切面类(内部有增强方法)
  4. 将目标类和切面类的对象创建权交给 spring
  5. 在 applicationContext.xml 中配置织入关系
  6. 测试代码
1.导入 AOP 相关坐标
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.3.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.13</version>
        </dependency>
2.创建目标接口和目标类(内部有切点)
public interface TargetInterface {
    public void save();
}
public class Target implements TargetInterface {
    public void save() {
        System.out.println("save running.......");
    }
}
3.创建切面类(内部有增强方法)
public class MyAspect {    
    //前置增强方法   
    public void before(){      
     System.out.println("前置代码增强.....");    
    }
 }
4将目标类和切面类的对象创建权交给 spring
<!--    目标对象-->
    <bean id="target" class="com.itlyt.aop.Target"></bean>

<!--    切面对象-->
    <bean id="myAspect" class="com.itlyt.aop.MyAspect"></bean>

5.配置织入
  导入aop命名空间
  xmlns:aop="http://www.springframework.org/schema/aop"
  http://www.springframework.org/schema/aop  http://www.springframework.org/schema/aop/spring-aop.xsd

  告诉spring框架 那些方法(切点)需要那些增强(前置...后置...<aop:config>
<!--    声明切面-->
<aop:aspect ref="myAspect">
<!--    切面:切点+通知-->
  <aop:before method="before" pointcut="execution(public void com.itlyt.aop.Target.save())"></aop:before>
</aop:aspect>
<aop:config>

6.测试代码(导入spring-test坐标)
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class AopTest {

    @Autowired
    private TargetInterface target;

    @Test
    public void test1(){
        target.save();
    }
}

基于注解的 AOP 开发

基于注解的aop开发步骤:

  1. 创建目标接口和目标类(内部有切点)
  2. 创建切面类(内部有增强方法)
  3. 将目标类和切面类的对象创建权交给 spring
  4. 在切面类中使用注解配置织入关系 在
  5. 配置文件中开启组件扫描和 AOP 的自动代理
  6. 测试
1.创建目标接口和目标类(内部有切点)
public interface TargetInterface {
    public void save();
}
public class Target implements TargetInterface {
    public void save() {
        System.out.println("save running.......");
    }
}
2.创建切面类(内部有增强方法)
public class MyAspect {    
   //前置增强方法    
   public void before(){     
    System.out.println("前置代码增强.....");    
   } 
 }
3.将目标类和切面类的对象创建权交给 spring
@Component("target")
public class Target implements TargetInterface {
    public void save() {
        System.out.println("save running.......");
    }
}
@Component("myAspect")
public class MyAspect {    
   //前置增强方法   
   public void before(){     
    System.out.println("前置代码增强.....");    
   } 
 }
4.在切面类中使用注解配置织入关系
@Component("myAspect")
@Aspect//标注当前MyAspect是一个切面类
public class MyAspect {    
   //前置增强方法    
   @Before("execution(* com.itheima.aop.*.*(..))")
   public void before(){     
    System.out.println("前置代码增强.....");    
   } 
 }
5.在配置文件中开启组件扫描和 AOP 的自动代理
<!--    组件扫描-->
    <context:component-scan base-package="com.itlyt.anno"/>
<!--    aop自动代理-->
    <aop:aspectj-autoproxy/>
6.测试代码
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext-anno.xml")
public class AnnoTest {

    @Autowired
    private TargetInterface target;

    @Test
    public void test1(){
        target.save();
    }
}


本文地址:https://blog.csdn.net/weixin_46111703/article/details/107350650

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网