2020-05-12:Spring—web实现AOP

实现步骤:
1.引入依赖jar包

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>3.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>3.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aopalliance</groupId>
<artifactId>com.springsource.org.aopalliance</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>com.springsource.org.aspectj.weaver</artifactId>
<version>1.6.4.RELEASE</version>
</dependency>
2.创建目标对象
//目标对象
public class TargetObj {
public void method1(){

    System.out.println(2);
    System.out.println(3);
}
public void method2(){

    System.out.println(2);
    System.out.println(3);
}

}
3.创建通知方法
//通知
public class MyAdvice {
public void one(){
System.out.println(1);
}
public void two(){
System.out.println(1);
}
}
4.添加ApplicationContext 配置
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

   xmlns:tx="http://www.springframework.org/schema/tx"

   xmlns:context="http://www.springframework.org/schema/context"

   xmlns:aop="http://www.springframework.org/schema/aop"

   xsi:schemaLocation="http://www.springframework.org/schema/beans

   http://www.springframework.org/schema/beans/spring-beans-2.5.xsd

   http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd

   http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd

   http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
<aop:config>
    <!--配置切面-->
    <aop:aspect ref="advice">
        <aop:before method="one" pointcut="execution(public void com.example.demo.module.aopTest.TargetObj.method1())"/>
        <aop:around method="two" pointcut="execution(public void com.example.demo.module.aopTest.TargetObj.method2())"/>
    </aop:aspect>

</aop:config>
<!--目标对象-->
<bean id="target" class="com.example.demo.module.aopTest.TargetObj"></bean>
<!--通知-->
<bean id="advice" class="com.example.demo.module.aopTest.MyAdvice"></bean>

</beans>
5.写测试类
public class AopDemo {
public static void main(String[] args) {
ApplicationContext cxt = new ClassPathXmlApplicationContext("applicationContext.xml");
Object bean = cxt.getBean("target");
TargetObj to=(TargetObj) bean;
to.method1();
System.out.println("-------------------");
to.method2();
}
}
关于aop简单的实现就完成了

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。