pom.xml
<!-- 添加spring-aop相应的jar包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring.version}</version>
</dependency>
AopConfigure.java(切面配置对象)
@Aspect
@Component
public class AopConfigure {
@Pointcut("execution(* com.lwb.*.*.*(..))")
public void recordLog() {}
@Before("recordLog()")
public void before() {
System.out.println("Before Attention!");
}
@After("recordLog()")
public void after() {
System.out.println("After Attention!");
}
/**
* @param pjp
* @param demoAno 注解类形参
* @throws Throwable
*/
@Around("recordLog() && @annotation(demoAno)")
public void around(ProceedingJoinPoint pjp , DemoAno demoAno) throws Throwable {
System.out.println("DemoAno annotation attribute desc: " + demoAno.desc());
System.out.println("DemoAno annotation attribute num: " + demoAno.num());
System.out.println("Around Attention!");
pjp.proceed();
System.out.println("After Exeute Around");
}
}
——————————————————————————————————————————————————————分割线————————————————————————————————————————————————————————
/* 需要在Spring配置文件中开启aop的自动代理 */
<aop:aspectj-autoproxy/>
单元测试&运行结果
@Test
public void five() {
//加载Spring配置文件
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring/spring-application.xml");
//通过Spring上下文对象获取OneService对象实例
OneService oneService = (OneService) context.getBean("oneService");
//执行one()方法
oneService.one();
}
运行结果