基于注解的測試Spring-aop通知順序
方法的接口
package com.bird.service;
public interface PersonServer {
public void save(String name);
public void update(String name, Integer id);
public String getPersonName(Integer id);
}
接口的實作
package com.bird.service.impl;
import com.bird.service.PersonServer;
public class PersonServiceBean implements PersonServer{
@Override
public void save(String name) {
System.out.println("我是save方法");
// throw new RuntimeException();
}
@Override
public void update(String name, Integer id) {
System.out.println("我是update()方法");
}
@Override
public String getPersonName(Integer id) {
System.out.println("我是getPersonName()方法");
return "xxx";
}
}
定義切點和通知
package com.bird.service;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
@Aspect
public class MyInterceptor {
@Pointcut("execution(* com.bird.service.impl.PersonServiceBean.*(..))")
private void anyMethod(){}//定義一個切入點
@Before("anyMethod() && args(name ,id)")
public void doAccessCheck(String name ,Integer id){
System.out.println(name + id);
System.out.println("前置通知+1");
}
@Before("anyMethod() && args(name )")
public void doAccessCheck1(String name ){
System.out.println(name );
System.out.println("前置通知");
}
@AfterReturning("anyMethod()")
public void doAfter(){
System.out.println("後置通知");
}
@After("anyMethod()")
public void after(){
System.out.println("最終通知");
}
@AfterThrowing("anyMethod()")
public void doAfterThrow(){
System.out.println("例外通知");
}
@Around("anyMethod()")
public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable{
System.out.println("進入環繞通知");
Object object = pjp.proceed();//執行該方法
System.out.println("退出方法");
return object;
}
}
Spring 的配置檔案
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<!-- 掃描com.ioc下的所有類,自動為spring容器管理 -->
<context:component-scan base-package="com.ioc"/>
</beans>
測試
package com.ioc;
import com.ioc.inerface.IPerson;
import com.ioc.util.BeanFactory;
public class SpringIocTest {
public static void main(String[] args) {
IPerson perSon = (IPerson) BeanFactory.getBean("person");
perSon.call();
BeanFactory.closeBeanFactory();
}
}