一、Spring Aop 代碼展示
接口:
public interface UserService {
String getById(Integer id);
}
實現類:
@Service
@Primary
@EnableAspectJAutoProxy(exposeProxy = true)
public class UserServiceImpl implements UserService {
@Override
public String getById(Integer id) {
System.out.println("userServiceImpl");
return "userService";
}
}
config 類
@ComponentScan({"com.lingtig"})
@Configuration
public class Appconfig {
}
Aop類:
@Aspect
@Component
public class AopTest {
@Around("execution(* com.luban.service.UserService.getById(..))")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
System.out.println("AOP before");
Object proceed = joinPoint.proceed();
System.out.println("AOP after");
return proceed;
}
}
main:
public static void main(String[] args) {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
applicationContext.register(Appconfig.class);
applicationContext.refresh();
UserService userServiceImpl = (UserService) applicationContext.getBean("userServiceImpl");
String ID = userServiceImpl.getById(12);
applicationContext.close();
}
最後的執行結果:
AOP before
userServiceImpl
AOP after
Spring aop源碼分析
一、思考代理對象什麼時候、在哪裏、怎麼生成?
我們在main方法裏,debug就能進入代理對象的invoke方法。JdkDynamicAopProxy就是userService的代理對象,此時的代理對象已經被增強。
我們找到JdkDynamicAopProxy的構造函數執行的代碼,進入到DefaultAopProxyFactory的createAopProxy方法。在這裏,我們打一個斷點。重新執行main方法。
執行的時序圖在這裏插入圖片描述
在bean初始化之後,abstractAutoProxyCreator類去執行postProcessAfterInitialization方法,abstractAutoProxyCreator是重寫了beanPostProcessor的後置處理器的postProcessAfterInitialization方法,在這個方面裏 ,創建了代理對象,實現了目標對象的增強。
到此已經說明了代理對象什麼時候創建、在哪裏創建、以及怎麼創建。
二、代理對象執行目標對象的方法的時候,怎麼對目標方法進行增強的呢?
在這裏插入圖片描述
在圖中,我們能看到此處獲取一系列攔截器chain,然後調用ReflectiveMethodInvocation的對象的proceed方法。
在這裏,依次遍歷攔截器,執行invoke方法,此處和我上一篇博客的Spring事務,是同一個原理,使用了責任鏈設計模式。