配置总applicationContext.xml:
<?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.Rain.service.UserServiceImpl"></bean>
<bean id="log" class="com.Rain.log.Log"></bean>
<bean id="afterLog" class="com.Rain.log.AfterLog"></bean>
<bean id="AnnotationPointCut" class="com.Rain.Diy.AnnotationPointCut"></bean>
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>
导入SpringAop包
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version> 1.9.4</version>
</dependency>
接口:
public interface UserService {
public void add();
public void delete();
public void update();
public void query();
}
实体类:
public class UserServiceImpl implements UserService{
@Override
public void add() {
System.out.println("增加了一个用户");
}
@Override
public void delete() {
System.out.println("删除了一个用户");
}
@Override
public void update() {
System.out.println("修改了一个用户");
}
@Override
public void query() {
System.out.println("查询了一个用户");
}
}
AnnotationPointCut类:
package com.Rain.Diy;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
@Aspect
public class AnnotationPointCut {
@Before("execution(* com.Rain.service.UserServiceImpl.*(..))")
public void before(){
System.out.println("=====方法执行前=====");
}
@After("execution(* com.Rain.service.UserServiceImpl.*(..))")
public void after(){
System.out.println("=====方法执行后=====");
}
@Around("execution(* com.Rain.service.UserServiceImpl.*(..))")
public void around(ProceedingJoinPoint jp) throws Throwable {
System.out.println("环绕前");
Object proceed = jp.proceed();
System.out.println("环绕后");
System.out.println(proceed);
}
}
DiyPointCut类:
public class DiyPointCut {
public void before(){
System.out.println("=========方法执行前=========");
}
public void after(){
System.out.println("=========方法执行后=========");
}
}
AfterLog类:
public class AfterLog implements AfterReturningAdvice {
@Override
public void afterReturning(Object o, Method method, Object[] objects, Object o1) throws Throwable {
System.out.println("执行了"+method.getName()+"方法,返回结果为:"+o);
}
}
log类:
public class Log implements MethodBeforeAdvice {
@Override
public void before(Method method, Object[] args, Object target) throws Throwable {
System.out.println(target.getClass().getName()+"的"+method.getName()+"被执行了!");
}
}