spring系列6-AOP实现

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/huanshirenjian/article/details/89599901

1.AOP

AOP是面向切面编程,在运行期间将某段代码切入到指定位置运行。

2. AOP注解实现

(1)注解类

@Aspect
@Component
public class AOPAspects {
	@Pointcut("execution(public * com.aaa.cap9.aop.Person.*(..))")
	public void pointCut() {};
	@Before("pointCut()")
	public void before() {
		System.out.println("before");
	}
	@After("pointCut()")
	public void after() {
		System.out.println("after");
	}
	@AfterReturning("pointCut()")
	public void returnInfo() {
		System.out.println("returnInfo");
	}
	@AfterThrowing("pointCut()")
	public void exceptionInfo() {
		System.out.println("exceptionInfo");
	}

}

(2)目标方法

@Component
public class Person {
	public int calc() {
		System.out.println("---calc----");
		return 1;
	}

}

(3)配置类

@Configuration
@EnableAspectJAutoProxy
@ComponentScan({"com.aaa.cap9.aop"})
public class Config {
}

(4)测试类

	AnnotationConfigApplicationContext app = new AnnotationConfigApplicationContext(Config .class);
		Person s = (Person) app.getBean(Person.class);
		int calc = s.calc();
		System.out.println("----------"+calc+"---");

注意类一定容器获得,不要直接new出来,否则aop不会生效。
输出结果:

before
---calc----
after
returnInfo
----------1---

(5)把calc方法修改下,抛出异常再看下输出结果

@Component
public class Person {
	public int calc() {
		System.out.println("---calc----");
		return 1/0;
	}

}
before
---calc----
after
exceptionInfo

(6)@Around是一个环绕注解,和以上几个注解组合起来使用类似。

@Aspect
@Component
public class AOPAspects2 {
	@Pointcut("execution(public * com.aaa.cap9.aop.Person.*(..))")
	public void pointCut() {};
	@Around("pointCut()")
	public Object exceptionInfo(ProceedingJoinPoint invocation) {
		try {
			System.out.println("before:");
			return invocation.proceed();
		} catch (Throwable e) {
			e.printStackTrace();
		}finally {
			System.out.println("afterturning:");
		}
		return null;
	}

输出结果

before:
---calc----
afterturning:
----------1---
``
`

猜你喜欢

转载自blog.csdn.net/huanshirenjian/article/details/89599901