1 注解方式aop基本使用
1.1 修改 UserServiceImpl
package com.study.service.impl;
import com.study.service.UserService;
import org.springframework.stereotype.Service;
@Service("userService")
public class UserServiceImpl implements UserService {
public void show1() {
System.out.println("UserServiceImpl -- show1");
}
public void show2() {
System.out.println("UserServiceImpl -- show2");
}
}
1.2 修改 MyAdvice
package com.study.advice;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
@Component
@Aspect
//增强类 内部提供增强方法
public class MyAdvice {
// <aop:before method="aroundAdvice" pointcut-ref="myPointcut"/>
@Before("execution(* com.study.service.impl.*.*(..))")
public void beforeAdvice(){
System.out.println("前置增强");
}
@AfterReturning("execution(* com.study.service.impl.*.*(..))")
public void afterAdvice(){
System.out.println("后置增强");
}
@Around("execution(* com.study.service.impl.*.*(..))")
public Object aroundAdvice(ProceedingJoinPoint proceedingJoinPoint) throws Throwable{
System.out.println("环绕前增强");
Object proceed = proceedingJoinPoint.proceed();
System.out.println("环绕后增强");
return proceed;
}
@AfterThrowing("execution(* com.study.service.impl.*.*(..))")
public void afterThrowingAdvice(){
System.out.println("异常抛出通知 报异常时执行");
}
}
1.3 新建配置文件 applicationContext2.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: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/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
">
<!--主键扫描-->
<context:component-scan base-package="com.study"/>
<!--开启注解配置aop-->
<aop:aspectj-autoproxy/>
</beans>
1.4 修改测试类
package com.study.demo;
import com.study.service.UserService;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class AspectDemo {
public static void main(String[] args) {
ClassPathXmlApplicationContext context =
new ClassPathXmlApplicationContext("applicationContext2.xml");
UserService userService = (UserService)context.getBean("userService");
userService.show1();
}
}