5

springboot(5)AOP代理

 2 years ago
source link: https://wakzz.cn/2018/01/22/springboot/(5)AOP%E4%BB%A3%E7%90%86/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

1、启动aop代理

添加maven依赖

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>

向springboot的入口类添加注解@EnableAspectJAutoProxy,使注解@Aspect生效。

2、aspect代理

@Aspect
@Component
public class TestAspect {

/**
* 在被拦截的方法执行前运行
*/
@Before("execution(* com.example.demo.action.*.* (..))")
public void testBefore() {
System.out.println("before");
}

/**
* 在被拦截的方法运行后运行
*/
@After("execution(* com.example.demo.action.*.* (..))")
public void testAfter() {
System.out.println("after");
}

/**
* 在被拦截的方法运行时运行
* @param pjp
* @throws Throwable
*/
@Around("execution(* com.example.demo.action.*.* (..))")
public Object testAround(ProceedingJoinPoint pjp) throws Throwable {
//在被拦截的方法执行前执行
System.out.println("before");
//执行被拦截的方法,并获取该方法返回的值
Object result = pjp.proceed();
System.out.println("==========="+result);
//在被拦截的方法执行后执行
System.out.println("after");
return result;
}

/**
* 在被拦截的方法抛出异常时运行
* @param e
*/
@AfterThrowing(pointcut="execution(* com.example.demo.action.*.* (..))",throwing="e")
public void testThrowing(Exception e) {
System.out.println(e.getMessage());
}
}

3、pointcut表达式

常用的pointcut表达式为execution,格式如下:
execution([访问修饰符] 返回类型 [申明类型] 方法名(参数名) [异常名])
|表达式|效果|
|—–|—–|—–|
|execution(public * * (..))|任意公共方法|
|execution(* set* (..))|任意方法名以”set”开头的方法|
|execution(* com.wxtx.TestDao.* (..))|com.wxtx.TestDao类下的任意方法|
|execution(* com.wxtx.. (..))|com.wxtx包(不包括子包)下的任意方法|
|execution(* com.wxtx... (..))|com.wxtx包及其子包下的任意方法|
|within(com.wxtx.service.)|com.wxtx.service包(不包括子包)下的任意方法|
|within(com.wxtx.service..
)|com.wxtx.service包(不包括子包)下的任意方法|
|this(com.wxtx.service.TestService)|实现了com.wxtx.service.TestService接口的代理对象的任意方法|
|target(com.wxtx.service.TestService)|实现了com.wxtx.service.TestService接口的目标对象的任意方法|
|args(java.io.Serializable)|任意只接受一个参数,且该参数类型是java.io.Serializable的方法|
|bean(testService)|spring容器中bean名为testSerivce的bean的任意方法|
|bean(Service)|spring容器中bean名匹配Serivce的bean的任意方法|


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK