public interface PersonService {
public void save(String name);
public void update(String name, Integer id);
public String getPersonName(Integer id);
}
public class PersonServiceImpl implements PersonService {
public String getPersonName(Integer id) {
System.out.println("我是getPersonName()方法");
return "xxx";
}
public void save(String name) {
throw new RuntimeException("我爱例外");
}
public void update(String name, Integer id) {
System.out.println("我是update()方法");
}
}
<strong>@Aspect</strong>
public class MyInterceptor {
<strong>@Pointcut</strong>("execution (* com.xxx.service.impl.PersonServiceImpl.*(..))")
private void anyMethod() {
}// 声明一个切入点
<strong>@Before</strong>("anyMethod() && args(name)")
public void doAccessCheck(String name) {
System.out.println("前置通知:" + name);
}
<strong>@AfterReturning</strong>(pointcut = "anyMethod()", returning = "result")
public void doAfterReturning(String result) {
System.out.println("后置通知:" + result);
}
<strong>@After</strong>("anyMethod()")
public void doAfter() {
System.out.println("最终通知");
}
<strong>@AfterThrowing</strong>(pointcut = "anyMethod()", throwing = "e")
public void doAfterThrowing(Exception e) {
System.out.println("例外通知:" + e);
}
<strong>@Around</strong>("anyMethod()")
public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable {
// if(){//判断用户是否在权限
System.out.println("进入方法");
Object result = pjp.proceed();
System.out.println("退出方法");
// }
return result;
}
}
<aop:aspectj-autoproxy/>
<bean id="personService" class="com.xxx.service.impl.PersonServiceImpl"/>
<bean id="myInterceptor" class="com.xxx.service.MyInterceptor"/>
@SuppressWarnings("resource")
@Test public void interceptorTest(){
ApplicationContext cxt = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
PersonService personService = (PersonService)cxt.getBean("personService");
personService.save("xx");
}