【纯注解方式比较麻烦,仅仅适用于个别方法配置,大面积方法配置需要结合xml】
- 配置applicationContext.xml
【注意】Spring不会自动寻找注解,需要引入新的命名空间——xmlns:context(多个包需要用逗号分割)来配置注解在那些包中
<?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.ouc.advice,com.ouc.demo"></context:component-scan>
<!--proxy-target-class
true 使用cglib动态代理
false 使用jdk动态代理
-->
<aop:aspectj-autoproxy proxy-target-class="true"></aop:aspectj-autoproxy>
</beans>
- 在Demo类中添加@Componet
(1)@Componet
① 相当于<bean/>
② 如果没有参数,把类名首字母变小写(如demo),相当于<bean/>
的id
③ 也可以自定义id,@Componet(“自定义名称”)
(2)@Pointcut(" ")定义切点
package com.ouc.demo;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
@Component
public class Demo {
@Pointcut("execution(* com.ouc.demo.Demo.demo1())")
public void demo1(){
//int i =5/0;
System.out.println("demo1");
}
}
- 在通知类中配置
(1)@Componet类被Spring管理
(2)@Aspect相当于<aop:aspect/>
,表示通知方法在当前类
package com.ouc.advice;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
@Component
@Aspect
public class MyAdvice {
@Before("com.ouc.demo.Demo.demo1()")
public void mybefore(){
System.out.println("前置");
}
@After("com.ouc.demo.Demo.demo1()")
public void myafter(){
System.out.println("后置");
}
/* @AfterThrowing("com.ouc.demo.Demo.demo1()")
public void mythrow(){
System.out.println("异常");
}*/
@Around("com.ouc.demo.Demo.demo1()")
public Object myarround(ProceedingJoinPoint p) throws Throwable{
System.out.println("执行环绕");
System.out.println("环绕-前置");
Object result = p.proceed();
System.out.println("环绕-后置");
return result;
}
}
- 测试类
package com.ouc.test;
import java.util.Arrays;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.ouc.demo.Demo;
public class Test {
public static void main(String[] args) throws Exception {
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
String[] list = ac.getBeanDefinitionNames();
System.out.println(Arrays.toString(list));
Demo demo = ac.getBean("demo", Demo.class);
demo.demo1();
}
}
- 结果
来源:CSDN
作者:Heart of Ocean
链接:https://blog.csdn.net/weixin_43180675/article/details/103733742