环绕通知
public interface SomeService {
String doFirst(String name,Integer age);
}
public class SomeServiceImpl implements SomeService {
@Override
public String doFirst(String name, Integer age) {
System.out.println("dofirst执行");
return "doFirst";
}
}
@Aspect
public class MyAspect {
/**
* 环绕通知
* 1.public
* 2.必须有一个返回值,推荐使用Object
* 3.方法名称自定义
* 4.方法有参数,固定的参数 ProceedingJoinPoint 继承了JoinPoint
* <p>
* 属性value:切入点表达式
* <p>
* 特点:
* 功能最强的通知
* 在目标方法的前和后都能增加功能
* 控制目标方法是否被调用执行
* 修改原来的目标方法的执行结果,影响最后的调用结果
* <p>
* 环境通知等同于jdk动态代理,InvocationHandler接口
* <p>
* 参数:ProceedingJoinPoint等同于jdk动态代理中的Method
* 作用:执行目标方法
*
* 经常做事务,在目标方法开始之前开始事务,方法执行完毕后提交事务
*
* @return 返回目标方法的执行结果,结果可以被修改
*/
@Around(value = "execution(* *..SomeService.doFirst(..))")
public Object myAround(ProceedingJoinPoint pj) {
Object result = null;
try {
System.out.println("增加输出时间:" + new Date());
result = pj.proceed();//相当于method.invoke()
System.out.println("模拟提交事务");
} catch (Throwable throwable) {
throwable.printStackTrace();
}
return result;
}
}
<bean class="com.demo.ba02.SomeServiceImpl" id="service"/>
<bean class="com.demo.ba02.MyAspect" id="aspect"/>
<aop:aspectj-autoproxy/>
public class MyTest {
@Test
public void test01(){
String config = "ApplicationContext.xml";
ApplicationContext ac = new ClassPathXmlApplicationContext(config);
SomeService service = (SomeService) ac.getBean("service");
String first = service.doFirst("zs", 20);
System.out.println(first);
}
}
影响返回结果:
@Around(value = "execution(* *..SomeService.doFirst(..))")
public Object myAround(ProceedingJoinPoint pj) {
Object result = null;
try {
System.out.println("增加输出时间:" + new Date());
result = pj.proceed();//相当于method.invoke()
result ="我可以改变结果";
System.out.println("模拟提交事务");
} catch (Throwable throwable) {
throwable.printStackTrace();
}
return result;
}
控制目标方法是否被调用执行:
@Around(value = "execution(* *..SomeService.doFirst(..))")
public Object myAround(ProceedingJoinPoint pj) {
Object result = null;
try {
System.out.println("增加输出时间:" + new Date());
Object[] args = pj.getArgs();
if ("zs".equals(args[0])){
result = pj.proceed();//相当于method.invoke()
}
System.out.println("模拟提交事务");
} catch (Throwable throwable) {
throwable.printStackTrace();
}
return result;
}
浙公网安备 33010602011771号