使用Spring AOP代理
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:ApplicationContext.xml")
public class AopTest {
@Autowired
private TargetInterface target;
@Test
public void test1(){
target.save();
}
}
<aop:config>
<aop:aspect ref="myAspect">
<!-- <aop:before method="beforeSave" pointcut="execution(public void com.qing.aop.*.*(..))"></aop:before>-->
<!-- <aop:after method="afterSave" pointcut="execution(public void com.qing.aop.Target.save())"></aop:after>-->
<aop:pointcut id="myPointcut" expression="execution(public void com.qing.aop.*.*(..))"/>
<aop:around method="around" pointcut-ref="myPointcut"></aop:around>
<aop:after-throwing method="afterThrowing" pointcut-ref="myPointcut"></aop:after-throwing>
<aop:after-returning method="afterReturning" pointcut-ref="myPointcut"></aop:after-returning>
<aop:after method="after" pointcut-ref="myPointcut"></aop:after>
</aop:aspect>
</aop:config>
注解开发
@Component("myAspect")
@Aspect //标注当前类是一个切面
public class MyAspect {
@Before("pointcut()")
public static void beforeSave(){
System.out.println("前置增强");
}
@AfterReturning("pointcut()")
public static void afterReturning(){
System.out.println("后置增强");
}
@After("pointcut()")
public static void after(){
System.out.println("最终增强");
}
@Around("pointcut()")
public static Object around(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("环绕前");
Object proceed = pjp.proceed(); //切点方法
System.out.println("环绕后");
return proceed;
}
@AfterThrowing("pointcut()")
public static void afterThrowing(){
System.out.println("异常!!!");
}
//定义切点表达式
@Pointcut("execution(public void com.qing.anno.*.*(..)))")
public void pointcut(){}
}
如果用SpringJunit集成,@RunWith(SpringJUnit4ClassRunner.class)有这个注解,就必须用注解配置configuration文件