使用Spring实现AOP
使用自定义类实现实现AOP
自定义类:
DefinePointCut
需要增强的实现类:
UserServiceImpl
XML配置文件:
applicationContext.xml
测试类:
MyTest
1 导入一个依赖
在pom.xml文件中导入依赖
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.7</version>
</dependency>
2 自定义类
创建DefinePointCut
package com.xzzlx.diy;
public class DefinePointCut {
public void before(){
System.out.println("*******方法执行之前********");
}
public void after(){
System.out.println("---------方法执行之后--------");
}
}
3 需要增强的执行类
package com.xzzlx.service;
public class UserServiceImpl implements UserService{
@Override
public void add() {
System.out.println("这是增加");
}
@Override
public void deleted() {
System.out.println("这是删除");
}
@Override
public void update() {
System.out.println("这是更改");
}
@Override
public void select() {
System.out.println("这是查询");
}
}
4 创建xml文件
导入aop “http://www.springframework.org/schema/aop”
<?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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<bean id="userService" class="com.xzzlx.service.UserServiceImpl"/>
<bean id="diy" class="com.xzzlx.diy.DefinePointCut"/>
<!--自定义-->
<aop:config>
<!--自定义切面,ref要引用的类-->
<aop:aspect ref="diy">
<!--切入点-->
<aop:pointcut id="point" expression="execution(* com.xzzlx.service.UserServiceImpl.*(..))"/>
<!--通知-->
<aop:before method="before" pointcut-ref="point"/>
<aop:after method="after" pointcut-ref="point"/>
</aop:aspect>
</aop:config>
</beans>
5 测试
创建测试类
import com.xzzlx.service.UserService;
import org.junit.jupiter.api.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
@Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = context.getBean("userService", UserService.class);
userService.select();
}
}
这个是自定义类实现AOP,有问题可以留言一起讨论~