初识AOP与尝试使用AOP

Aspect Oriented Programming 面向切面编程

AOP的底层实现是动态代理,在实际工作的对象与用户之间加一层代理,一般来说,对象只要关注纯粹的工作,可以把公共的动作提取出来放在代理层。就像 房主-中介-租客 一样,房主只需要做提供房屋的工作,而公共的寻找租客,签合同就提取出来交给中介来做,中介就是代理。从前面可以看出,AOP可以在不修改原来代码的情况下对“输出内容”进行修改(增加)

AOP的使用

可以通过三种方法使用AOP,使用spring的API、自定义实现AOP和使用注解。这里我来介绍方法二
要使用AOP首先要导入依赖

		<dependency>
            <groupId>org.aspectjgroupId>
            <artifactId>aspectjweaverartifactId>
            <version>1.9.6version>
        dependency>

然后编写要被代理的类

package com.wt.service;

public class TestClass {
     
    public void test00(){
     
        System.out.println("service正在执行");
    }
}

再编写代理的方法(切面)

package com.wt.diy;

public class DiyPointCut {
     

    public void before(){
     
        System.out.println("===========执行方法前============");
    }

    public void after(){
     
        System.out.println("===========执行方法后============");
    }

}

在xml文件中注册


<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/c"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">


    <context:annotation-config/>

    <bean id="diy" class="com.wt.diy.DiyPointCut"/>
    <bean id="service" class="com.wt.service.TestClass"/>

    <aop:config>
        
        <aop:aspect ref="diy">
            
            <aop:ponitcut id="point" expression="execution(* com.wt.service.*.*(..))"/>
            
            <aop:before method="before" ponitcut-ref="point"/>
            <aop:after method="after" ponitcut-ref="point"/>
        aop:aspect>
    aop:config>
beans>

测试

import com.wt.service.TestClass;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
     
    public static void main(String[] args) {
     
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml") ;
        TestClass testClass = context.getBean("service",TestClass.class);

        testClass.test00();
    }
}

你可能感兴趣的:(java,spring,aop)