<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.wantong</groupId>
<artifactId>Spring_AOP_Annotation</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!-- Spring常用依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>5.1.8.RELEASE</version>
</dependency>
</dependencies>
</project>
@Repository
public class UserDaoImpl implements UserDao {
@Override
public void addUser(){
System.out.println("insert into tb_user......");
}
}
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
public void addUser() {
userDao.addUser();
}
}
<?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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.wantong"></context:component-scan>
</beans>
/**
* 模拟表现层
*/
public class Client {
public static void main(String[] args) {
ApplicationContext ac =
new ClassPathXmlApplicationContext("applicationContext.xml");
//使用对象
UserService userService = ac.getBean("userServiceImpl",UserService.class);
userService.addUser();
}
}
<!-- 开启spring对注解AOP的支持 -->
<aop:aspectj-autoproxy/>
常用注解
注解方式实现aop
@Component
@Aspect
public class MyLogAdvice {
//前置通知
@Before("execution(* com.wantong.service.*.*(..))")
public void before(){
System.out.println("前置通知");
}
//后置通知【try】
@AfterReturning("execution(* com.wantong.service.*.*(..))")
public void afterReturning(){
System.out.println("后置通知");
}
//异常通知【catch】
@AfterThrowing("execution(* com.wantong.service.*.*(..))")
public void afterThrowing(){
System.out.println("异常通知");
}
//最终通知【finally】
@After("execution(* com.wantong.service.*.*(..))")
public void after(){
System.out.println("最终通知");
}
//环绕通知
@Around("execution(* com.wantong.service.*.*(..))")
public void around(ProceedingJoinPoint joinPoint){
try {
System.out.println("方法执行前的环绕通知");
joinPoint.proceed();
System.out.println("方法执行后的环绕通知");
} catch (Throwable throwable) {
throwable.printStackTrace();
}
}
}