我們在前文中已經介紹了SpringAOP的切面實現和建立動態代理的過程,那麼動態代理是如何工作的呢?本文主要介紹Cglib動態代理的案例和SpringAOP實現的原理。@pdai
我們在前文中已經介紹了SpringAOP的切面實現和建立動態代理的過程,那麼動態代理是如何工作的呢?本文主要介紹Cglib動態代理的案例和SpringAOP實現的原理。
要了解動態代理是如何工作的,首先需要了解
代理模式(Proxy pattern): 為另一個物件提供一個替身或預留位置以控制對這個物件的存取
舉個簡單的例子:
我(client)如果要買(doOperation)房,可以找中介(proxy)買房,中介直接和賣方(target)買房。中介和賣方都實現買賣(doOperation)的操作。中介就是代理(proxy)。
動態代理就是,在程式執行期,建立目標物件的代理物件,並對目標物件中的方法進行功能性增強的一種技術。
在生成代理物件的過程中,目標物件不變,代理物件中的方法是目標物件方法的增強方法。可以理解為執行期間,物件中方法的動態攔截,在攔截方法的前後執行功能操作。
Cglib是一個強大的、高效能的程式碼生成包,它廣泛被許多AOP框架使用,為他們提供方法的攔截。
這裡我們寫一個使用cglib的簡單例子。@pdai
引入cglib的依賴包
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>tech-pdai-spring-demos</artifactId>
<groupId>tech.pdai</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>007-spring-framework-demo-aop-proxy-cglib</artifactId>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/cglib/cglib -->
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>3.3.0</version>
</dependency>
</dependencies>
</project>
User
package tech.pdai.springframework.entity;
/**
* @author pdai
*/
public class User {
/**
* user's name.
*/
private String name;
/**
* user's age.
*/
private int age;
/**
* init.
*
* @param name name
* @param age age
*/
public User(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
即目標類, 對被代理的類中的方法進行增強
package tech.pdai.springframework.service;
import java.util.Collections;
import java.util.List;
import tech.pdai.springframework.entity.User;
/**
* @author pdai
*/
public class UserServiceImpl {
/**
* find user list.
*
* @return user list
*/
public List<User> findUserList() {
return Collections.singletonList(new User("pdai", 18));
}
/**
* add user
*/
public void addUser() {
// do something
}
}
cglib代理類,需要實現MethodInterceptor介面,並指定代理目標類target
package tech.pdai.springframework.proxy;
import java.lang.reflect.Method;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
/**
* This class is for proxy demo.
*
* @author pdai
*/
public class UserLogProxy implements MethodInterceptor {
/**
* 業務類物件,供代理方法中進行真正的業務方法呼叫
*/
private Object target;
public Object getUserLogProxy(Object target) {
//給業務物件賦值
this.target = target;
//建立加強器,用來建立動態代理類
Enhancer enhancer = new Enhancer();
//為加強器指定要代理的業務類(即:為下面生成的代理類指定父類別)
enhancer.setSuperclass(this.target.getClass());
//設定回撥:對於代理類上所有方法的呼叫,都會呼叫CallBack,而Callback則需要實現intercept()方法進行攔
enhancer.setCallback(this);
// 建立動態代理類物件並返回
return enhancer.create();
}
// 實現回撥方法
@Override
public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
// log - before method
System.out.println("[before] execute method: " + method.getName());
// call method
Object result = proxy.invokeSuper(obj, args);
// log - after method
System.out.println("[after] execute method: " + method.getName() + ", return value: " + result);
return null;
}
}
啟動類中指定代理目標並執行。
package tech.pdai.springframework;
import tech.pdai.springframework.proxy.UserLogProxy;
import tech.pdai.springframework.service.UserServiceImpl;
/**
* Cglib proxy demo.
*
* @author pdai
*/
public class ProxyDemo {
/**
* main interface.
*
* @param args args
*/
public static void main(String[] args) {
// proxy
UserServiceImpl userService = (UserServiceImpl) new UserLogProxy().getUserLogProxy(new UserServiceImpl());
// call methods
userService.findUserList();
userService.addUser();
}
}
我們啟動上述類main 函數,執行的結果如下:
[before] execute method: findUserList
[after] execute method: findUserList, return value: [User{name='pdai', age=18}]
[before] execute method: addUser
[after] execute method: addUser, return value: null
我們把上述Demo的主要流程畫出來,你便能很快理解
更多細節:
SpringAOP封裝了cglib,通過其進行動態代理的建立。
我們看下CglibAopProxy的getProxy方法
@Override
public Object getProxy() {
return getProxy(null);
}
@Override
public Object getProxy(@Nullable ClassLoader classLoader) {
if (logger.isTraceEnabled()) {
logger.trace("Creating CGLIB proxy: " + this.advised.getTargetSource());
}
try {
Class<?> rootClass = this.advised.getTargetClass();
Assert.state(rootClass != null, "Target class must be available for creating a CGLIB proxy");
// 上面流程圖中的目標類
Class<?> proxySuperClass = rootClass;
if (rootClass.getName().contains(ClassUtils.CGLIB_CLASS_SEPARATOR)) {
proxySuperClass = rootClass.getSuperclass();
Class<?>[] additionalInterfaces = rootClass.getInterfaces();
for (Class<?> additionalInterface : additionalInterfaces) {
this.advised.addInterface(additionalInterface);
}
}
// Validate the class, writing log messages as necessary.
validateClassIfNecessary(proxySuperClass, classLoader);
// 重點看這裡,就是上圖的enhancer,設定各種引數來構建
Enhancer enhancer = createEnhancer();
if (classLoader != null) {
enhancer.setClassLoader(classLoader);
if (classLoader instanceof SmartClassLoader &&
((SmartClassLoader) classLoader).isClassReloadable(proxySuperClass)) {
enhancer.setUseCache(false);
}
}
enhancer.setSuperclass(proxySuperClass);
enhancer.setInterfaces(AopProxyUtils.completeProxiedInterfaces(this.advised));
enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE);
enhancer.setStrategy(new ClassLoaderAwareGeneratorStrategy(classLoader));
// 設定callback回撥介面,即方法的增強點
Callback[] callbacks = getCallbacks(rootClass);
Class<?>[] types = new Class<?>[callbacks.length];
for (int x = 0; x < types.length; x++) {
types[x] = callbacks[x].getClass();
}
// 上節說到的filter
enhancer.setCallbackFilter(new ProxyCallbackFilter(
this.advised.getConfigurationOnlyCopy(), this.fixedInterceptorMap, this.fixedInterceptorOffset));
enhancer.setCallbackTypes(types);
// 重點:建立proxy和其範例
return createProxyClassAndInstance(enhancer, callbacks);
}
catch (CodeGenerationException | IllegalArgumentException ex) {
throw new AopConfigException("Could not generate CGLIB subclass of " + this.advised.getTargetClass() +
": Common causes of this problem include using a final class or a non-visible class",
ex);
}
catch (Throwable ex) {
// TargetSource.getTarget() failed
throw new AopConfigException("Unexpected AOP exception", ex);
}
}
獲取callback的方法如下,提幾個理解的要點吧,具體讀者在學習的時候建議把我的例子跑一下,然後打一個斷點進行理解。
rootClass
: 即目標代理類advised
: 包含上文中我們獲取到的advisor增強器的集合exposeProxy
: 在xml組態檔中設定的,背景就是如果在事務A中使用了代理,事務A呼叫了目標類的的方法a,在方法a中又呼叫目標類的方法b,方法a,b同時都是要被增強的方法,如果不設定exposeProxy屬性,方法b的增強將會失效,如果設定exposeProxy,方法b在方法a的執行中也會被增強了DynamicAdvisedInterceptor
: 攔截器將advised(包含上文中我們獲取到的advisor增強器)構建設定的AOP的callback(第一個callback)targetInterceptor
: xml設定的optimize屬性使用的(第二個callback)private Callback[] getCallbacks(Class<?> rootClass) throws Exception {
// Parameters used for optimization choices...
boolean exposeProxy = this.advised.isExposeProxy();
boolean isFrozen = this.advised.isFrozen();
boolean isStatic = this.advised.getTargetSource().isStatic();
// Choose an "aop" interceptor (used for AOP calls).
Callback aopInterceptor = new DynamicAdvisedInterceptor(this.advised);
// Choose a "straight to target" interceptor. (used for calls that are
// unadvised but can return this). May be required to expose the proxy.
Callback targetInterceptor;
if (exposeProxy) {
targetInterceptor = (isStatic ?
new StaticUnadvisedExposedInterceptor(this.advised.getTargetSource().getTarget()) :
new DynamicUnadvisedExposedInterceptor(this.advised.getTargetSource()));
}
else {
targetInterceptor = (isStatic ?
new StaticUnadvisedInterceptor(this.advised.getTargetSource().getTarget()) :
new DynamicUnadvisedInterceptor(this.advised.getTargetSource()));
}
// Choose a "direct to target" dispatcher (used for
// unadvised calls to static targets that cannot return this).
Callback targetDispatcher = (isStatic ?
new StaticDispatcher(this.advised.getTargetSource().getTarget()) : new SerializableNoOp());
Callback[] mainCallbacks = new Callback[] {
aopInterceptor, //
targetInterceptor, // invoke target without considering advice, if optimized
new SerializableNoOp(), // no override for methods mapped to this
targetDispatcher, this.advisedDispatcher,
new EqualsInterceptor(this.advised),
new HashCodeInterceptor(this.advised)
};
Callback[] callbacks;
// If the target is a static one and the advice chain is frozen,
// then we can make some optimizations by sending the AOP calls
// direct to the target using the fixed chain for that method.
if (isStatic && isFrozen) {
Method[] methods = rootClass.getMethods();
Callback[] fixedCallbacks = new Callback[methods.length];
this.fixedInterceptorMap = CollectionUtils.newHashMap(methods.length);
// TODO: small memory optimization here (can skip creation for methods with no advice)
for (int x = 0; x < methods.length; x++) {
Method method = methods[x];
List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, rootClass);
fixedCallbacks[x] = new FixedChainStaticTargetInterceptor(
chain, this.advised.getTargetSource().getTarget(), this.advised.getTargetClass());
this.fixedInterceptorMap.put(method, x);
}
// Now copy both the callbacks from mainCallbacks
// and fixedCallbacks into the callbacks array.
callbacks = new Callback[mainCallbacks.length + fixedCallbacks.length];
System.arraycopy(mainCallbacks, 0, callbacks, 0, mainCallbacks.length);
System.arraycopy(fixedCallbacks, 0, callbacks, mainCallbacks.length, fixedCallbacks.length);
this.fixedInterceptorOffset = mainCallbacks.length;
}
else {
callbacks = mainCallbacks;
}
return callbacks;
}
可以結合偵錯,方便理解
https://github.com/realpdai/tech-pdai-spring-demos
首先, 從Spring框架的整體架構和組成對整體框架有個認知。
其次,通過案例引出Spring的核心(IoC和AOP),同時對IoC和AOP進行案例使用分析。
基於Spring框架和IOC,AOP的基礎,為構建上層web應用,需要進一步學習SpringMVC。
Spring進階 - IoC,AOP以及SpringMVC的原始碼分析
ConcurrentHashMap<String, Object>
;並且BeanDefinition介面中包含了這個類的Class資訊以及是否是單例等。那麼如何從BeanDefinition中範例化Bean物件呢,這是本文主要研究的內容?