在Spring代理目標bean的時候,其並不是直接創建一個目標bean的對象實例的,而是通過一個TargetSource
類型的對象將目標bean進行封裝,Spring Aop獲取目標對象始終是通過TargetSource.getTarget()
方法進行的。本文首先會講解Spring Aop是如何封裝目標對象到TargetSource
中的,然後會講解TargetSource
各個方法的使用原理,接着會對Spring提供的常見的TargetSource
的實現類進行講解,最後會講解如何實現自定義的TargetSource
。
1. 封裝TargetSource對象
我們知道,Spring Aop標籤解析的最終結果就是生成了一個AnnotationAwareAspectJAutoProxyCreator
的BeanDefinition
,我們查看這個類的繼承結構可以發現其實現了InstantiationAwareBeanPostProcessor
和BeanPostProcessor
兩個接口,並且分別實現了下面兩個方法:
- public interface InstantiationAwareBeanPostProcessor extends BeanPostProcessor {
- @Nullable
- default Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName)
- throws BeansException {
- return null;
- }
- }
- public interface BeanPostProcessor {
- @Nullable
- default Object postProcessAfterInitialization(Object bean, String beanName)
- throws BeansException {
- return bean;
- }
- }
這裏省略了其餘的不相關方法。上述第一個方法會在Spring實例化一個bean之前執行,如果這裏第一個方法能夠返回目標bean對象,那麼這裏就直接使用該對象,Spring不會繼續生成目標bean對象,這種方式可以實現自定義的bean對象;而第二個方法會在Spring實例化一個bean之後執行,主要作用是對已經生成的bean進行一定的處理。這裏AnnotationAwareAspectJAutoProxyCreator
對這兩個方法都進行了重寫,對於重寫的第一個方法,其主要目的在於如果用戶使用了自定義的TargetSource
對象,則直接使用該對象生成目標對象,而不會使用Spring的默認邏輯生成目標對象,並且這裏會判斷各個切面邏輯是否可以應用到當前bean上,如果可以,則直接應用,也就是說TargetSource
爲使用者在Aop中提供了一個自定義生成目標bean邏輯的方式,並且會應用相應的切面邏輯。對於第二個方法,其主要作用在於Spring生成某個bean之後,將相關的切面邏輯應用到該bean上,這個方法在後續將會詳細講解。這裏主要講解第一方法的原理,如下是其實現源碼:
- @Override
- public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName)
- throws BeansException {
- Object cacheKey = getCacheKey(beanClass, beanName);
-
- // 判斷TargetSource緩存中是否包含當前bean,如果不包含,則判斷當前bean是否是已經被代理的bean,
- // 如果代理過,則不對當前傳入的bean進行處理,如果沒代理過,則判斷當前bean是否爲系統bean,或者是
- // 切面邏輯不會包含的bean,如果是,則將當前bean緩存到advisedBeans中,否則繼續往下執行。
- // 經過這一步的處理之後,只有在TargetSource中沒有進行緩存,並且應該被切面邏輯環繞,但是目前還未
- // 生成代理對象的bean纔會通過此方法。
- if (!StringUtils.hasLength(beanName) || !this.targetSourcedBeans.contains(beanName)) {
- if (this.advisedBeans.containsKey(cacheKey)) {
- return null;
- }
- if (isInfrastructureClass(beanClass) || shouldSkip(beanClass, beanName)) {
- this.advisedBeans.put(cacheKey, Boolean.FALSE);
- return null;
- }
- }
-
- // 獲取封裝當前bean的TargetSource對象,如果不存在,則直接退出當前方法,否則從TargetSource
- // 中獲取當前bean對象,並且判斷是否需要將切面邏輯應用在當前bean上。
- TargetSource targetSource = getCustomTargetSource(beanClass, beanName);
- if (targetSource != null) {
- if (StringUtils.hasLength(beanName)) {
- this.targetSourcedBeans.add(beanName);
- }
-
- // 獲取能夠應用當前bean的切面邏輯
- Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(beanClass,
- beanName, targetSource);
- // 根據切面邏輯爲當前bean生成代理對象
- Object proxy = createProxy(beanClass, beanName, specificInterceptors,
- targetSource);
- // 對生成的代理對象進行緩存
- this.proxyTypes.put(cacheKey, proxy.getClass());
- // 直接返回生成的代理對象,從而使後續bean的創建工作短路
- return proxy;
- }
-
- return null;
- }
2. TargetSource使用原理
如下是TargetSource
接口的聲明:
- public interface TargetSource extends TargetClassAware {
-
- // 本方法主要用於返回目標bean的Class類型
- @Override
- @Nullable
- Class<?> getTargetClass();
-
- // 這個方法用戶返回當前bean是否爲靜態的,比如常見的單例bean就是靜態的,而prototype就是動態的,
- // 這裏這個方法的主要作用是,對於靜態的bean,spring是會對其進行緩存的,在多次使用TargetSource
- // 獲取目標bean對象的時候,其獲取的總是同一個對象,通過這種方式提高效率
- boolean isStatic();
-
- // 獲取目標bean對象,這裏可以根據業務需要進行自行定製
- @Nullable
- Object getTarget() throws Exception;
-
- // Spring在完目標bean之後會調用這個方法釋放目標bean對象,對於一些需要池化的對象,這個方法是必須
- // 要實現的,這個方法默認不進行任何處理
- void releaseTarget(Object target) throws Exception;
- }
3. Spring提供的TargetSource對象
通過第二節對TargetSource
的聲明和使用原理講解,我們可以看到,TargetSource接口的設計幾乎爲我們使用該接口實現自定義的對象實現了各種可能性:單例,多例,池化對象等等。下面我們看看Spring爲我們提供了哪些常見的TargetSource
實現類:
3.1 SingletonTargetSource
SingletonTargetSource
,顧名思義,即爲單例的TargetSource
,其只是對目標bean進行了簡單的封裝。如下是其實現源碼:
- public class SingletonTargetSource implements TargetSource, Serializable {
- private static final long serialVersionUID = 9031246629662423738L;
- private final Object target;
-
- public SingletonTargetSource(Object target) {
- Assert.notNull(target, "Target object must not be null");
- this.target = target;
- }
-
- @Override
- public Class<?> getTargetClass() {
- return this.target.getClass();
- }
-
- @Override
- public Object getTarget() {
- return this.target;
- }
-
- @Override
- public void releaseTarget(Object target) {}
-
- @Override
- public boolean isStatic() {
- return true;
- }
- }
可以看到SingletonTargetSource
通過構造方法傳入一個目標bean對象,在使用getTarget()
方法時,也只是將該對象直接返回;並且這裏isStatic()
方法返回的是true,也就是說,Spring是可以緩存SingletonTargetSource
的。
3.2 PrototypeTargetSource
與SingletonTargetSource
類似,PrototypeTargetSource
表示其將生成prototype類型的bean,即其生成的bean並不是單例的,因而使用這個類型的TargetSource
時需要注意,封裝的目標bean必須是prototype類型的。如下是其實現源碼:
- public class PrototypeTargetSource extends AbstractPrototypeBasedTargetSource {
-
- @Override
- public Object getTarget() throws BeansException {
- return newPrototypeInstance();
- }
-
- @Override
- public void releaseTarget(Object target) {
- destroyPrototypeInstance(target);
- }
- }
可以看到PrototypeTargetSource
主要重寫了getTarget()
和releaseTarget()
方法,並且委託給newPrototypeInstance()
和destroyPrototypeInstance()
執行。我們這裏看看AbstractPrototypeBasedTargetSource
的源碼:
- public abstract class AbstractPrototypeBasedTargetSource
- extends AbstractBeanFactoryBasedTargetSource {
-
- // 繼承自BeanFactoryAware接口,將當前Spring使用的BeanFactory傳進來
- @Override
- public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
- super.setBeanFactory(beanFactory);
- if (!beanFactory.isPrototype(getTargetBeanName())) {
- throw new BeanDefinitionStoreException(
- "Cannot use prototype-based TargetSource
- + "against non-prototype bean with name '"
- + getTargetBeanName() + "': instances would not be independent");
- }
- }
- // 使用BeanFactory獲取目標bean的對象,getTargetBeanName()方法將返回目標bean的名稱,
- // 由於目標bean是prototype類型的,因而這裏也就可以通過BeanFactory獲取prototype類型的bean
- // 這也是PrototypeTargetSource能夠生成prototype類型的bean的根本原因
- protected Object newPrototypeInstance() throws BeansException {
- if (logger.isDebugEnabled()) {
- logger.debug("Creating new instance of bean '" + getTargetBeanName() + "'");
- }
- return getBeanFactory().getBean(getTargetBeanName());
- }
- // 如果生成的bean使用完成,則會調用當前方法銷燬目標bean,由於目標bean可能實現了DisposableBean
- // 接口,因而這裏銷燬bean的方式就是調用其實現的該接口的方法,從而銷燬目標bean
- protected void destroyPrototypeInstance(Object target) {
- if (this.logger.isDebugEnabled()) {
- this.logger.debug("Destroying instance of bean '"
- + getTargetBeanName() + "'");
- }
- if (getBeanFactory() instanceof ConfigurableBeanFactory) {
- ((ConfigurableBeanFactory) getBeanFactory())
- .destroyBean(getTargetBeanName(), target);
- } else if (target instanceof DisposableBean) {
- try {
- ((DisposableBean) target).destroy();
- } catch (Throwable ex) {
- logger.error("Couldn't invoke destroy method of bean with name '"
- + getTargetBeanName() + "'", ex);
- }
- }
- }
- }
可以看到,PrototypeTargetSource
的生成prototype類型bean的方式主要是委託給BeanFactory
進行的,因爲BeanFactory
自有一套生成prototype類型的bean的邏輯,因而PrototypeTargetSource
也就具有生成prototype類型bean的能力,這也就是我們要生成的目標bean必須聲明爲prototype類型的原因。
3.3 CommonsPool2TargetSource
這裏CommonsPool2TargetSource
也就是池化的TargetSource
,其基本具有平常所使用的“池”的概念的所有屬性,比如:最小空閒數,最大空閒數,最大等待時間等等。實際上,CommonsPool2TargetSource
的實現是將其委託給了ObjectPool
進行,具體的也就是GenericObjectPool
,其實現了ObjectPool
接口。如下是CommonsPool2TargetSource
的主要實現:
- public class CommonsPool2TargetSource extends AbstractPoolingTargetSource implements PooledObjectFactory<Object> {
-
- // 保存池化對象的池
- @Nullable
- private ObjectPool pool;
-
- public CommonsPool2TargetSource() {
- setMaxSize(GenericObjectPoolConfig.DEFAULT_MAX_TOTAL);
- }
-
- @Override
- protected final void createPool() {
- logger.debug("Creating Commons object pool");
- // 創建池化對象
- this.pool = createObjectPool();
- }
-
- // 設置池化對象的基本屬性
- protected ObjectPool createObjectPool() {
- GenericObjectPoolConfig config = new GenericObjectPoolConfig();
- config.setMaxTotal(getMaxSize());
- config.setMaxIdle(getMaxIdle());
- config.setMinIdle(getMinIdle());
- config.setMaxWaitMillis(getMaxWait());
- config.setTimeBetweenEvictionRunsMillis(getTimeBetweenEvictionRunsMillis());
- config.setMinEvictableIdleTimeMillis(getMinEvictableIdleTimeMillis());
- config.setBlockWhenExhausted(isBlockWhenExhausted());
- return new GenericObjectPool(this, config);
- }
-
- // 從池中請求目標對象
- @Override
- public Object getTarget() throws Exception {
- Assert.state(this.pool != null, "No Commons ObjectPool available");
- return this.pool.borrowObject();
- }
-
- // 將目標對象歸還到池中
- @Override
- public void releaseTarget(Object target) throws Exception {
- if (this.pool != null) {
- this.pool.returnObject(target);
- }
- }
- }
可以看到CommonsPool2TargetSource
實現是非常簡單的,其將主要功能都委託給了對象池進行,這裏的對象池實現也比較簡單,其主要使用LinkedBlockingDeque
,也就是可阻塞的雙端隊列實現對象池的功能。這裏關於隊列鎖的使用並不是本文的研究範疇,讀者可閱讀本人前面的文章進行多線程的學習。
3.4 ThreadLocalTargetSource
ThreadLocalTargetSource
也就是和線程綁定的TargetSource
,可以理解,其底層實現必然使用的是ThreadLocal
。既然使用了ThreadLocal
,也就是說我們需要注意兩個問題:
- 目標對象必須聲明爲prototype類型,因爲每個線程都會持有一個不一樣的對象;
- 目標對象必須是無狀態的,因爲目標對象是和當前線程綁定的,而Spring是使用的線程池處理的請求,因而每個線程可能處理不同的請求,因而爲了避免造成問題,目標對象必須是無狀態的。
如下是ThreadLocalTargetSource
的源碼:
- public class ThreadLocalTargetSource extends AbstractPrototypeBasedTargetSource
- implements ThreadLocalTargetSourceStats, DisposableBean {
-
- // 保存目標對象的ThreadLocal對象
- private final ThreadLocal<Object> targetInThread =
- new NamedThreadLocal<>("Thread-local instance of bean '"
- + getTargetBeanName() + "'");
-
- // 將生成過的目標對象保存起來,以便於後續進行統一銷燬
- private final Set<Object> targetSet = new HashSet<>();
-
- // 生成目標對象,這裏的生成方式是ThreadLocal很典型的一種使用策略,即首先從ThreadLocal中取,
- // 如果取到了,則直接返回,如果沒取到,則使用“消耗“大一些的方式獲取,並緩存到ThreadLocal中
- @Override
- public Object getTarget() throws BeansException {
- // 記錄目標對象的獲取次數
- ++this.invocationCount;
- // 從ThreadLocal中獲取
- Object target = this.targetInThread.get();
- if (target == null) {
- if (logger.isDebugEnabled()) {
- logger.debug("No target for prototype '" + getTargetBeanName()
- + "' bound to thread: " + "creating one and binding it to thread '"
- + Thread.currentThread().getName() + "'");
- }
- // 如果ThreadLocal中不存在,則通過最基本的方式獲取目標對象,
- // 並將生成的對象保存到ThreadLocal中
- target = newPrototypeInstance();
- this.targetInThread.set(target);
- // 將生成的對象進行緩存
- synchronized (this.targetSet) {
- this.targetSet.add(target);
- }
- }
- else {
- ++this.hitCount;
- }
- return target;
- }
-
- // 銷燬當前TargetSource對象和生成的目標對象
- @Override
- public void destroy() {
- logger.debug("Destroying ThreadLocalTargetSource bindings");
- synchronized (this.targetSet) {
- for (Object target : this.targetSet) {
- // 銷燬生成的目標對象
- destroyPrototypeInstance(target);
- }
- this.targetSet.clear();
- }
- // 清除ThreadLocal中的緩存
- this.targetInThread.remove();
- }
- }
這裏ThreadLocalTargetSource
主要集成了AbstractPrototypeBasedTargetSource
和DisposableBean
。關於AbstractPrototypeBasedTargetSource
前面已經講過了,讀者可以到前面翻看;而DisposableBean
的作用主要是提供一個方法,以供給Spring在銷燬當前對象的時候調用。也就是說Spring在銷燬當前TargetSource
對象的時候會首先銷燬其生成的各個目標對象。這裏需要注意的是,TargetSource
和生成的目標對象是兩個對象,前面講的TargetSouce
都是單例的,只是生成的目標對象可能是單例的,也可能是多例的。
4. 實現自定義的TargetSource
對前面各個TargetSource
掌握之後,要實現自定義的TargetSource
實際上也非常的簡單,假設我們這裏要生成兩個對象進行訪問均衡,此時就可以使用自定義的TargetSource
。如下是我們要生成的目標對象的聲明:
- public class Apple {
- private int id;
-
- public Apple(int id) {
- this.id = id;
- }
-
- public void eat() {
- System.out.println("eat apple, id: " + id);
- }
- }
這裏Apple對象使用id屬性進行當前對象的標識,並在eat()
方法中將id打印出來了。如下是自定義TargetSource
實現:
- public class AppleTargetSource implements TargetSource {
- private Apple apple1;
- private Apple apple2;
-
- public AppleTargetSource() {
- this.apple1 = new Apple(1);
- this.apple2 = new Apple(2);
- }
-
- @Override
- public Class<?> getTargetClass() {
- return Apple.class;
- }
-
- @Override
- public boolean isStatic() {
- return false;
- }
-
- @Override
- public Object getTarget() throws Exception {
- ThreadLocalRandom random = ThreadLocalRandom.current();
- int index = random.nextInt(2);
- return index % 2 == 0 ? apple1 : apple2;
- }
-
- @Override
- public void releaseTarget(Object target) throws Exception {}
- }
實現自定義TargetSource
主要有兩個點要注意,一個是getTarget()
方法,該方法中需要實現獲取目標對象的邏輯,另一個是isStatic()
方法,這個方法告知Spring是否需要緩存目標對象,在非單例的情況下一般是返回false。如下是xml文件配置和驅動類的實現:
- <?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:aop="http://www.springframework.org/schema/aop"
- xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
-
- <bean id="targetSource" class="chapter7.eg10.AppleTargetSource"/>
- <aop:aspectj-autoproxy/>
- </beans>
- public class CustomTargetSourceApp {
- public static void main(String[] args) throws Exception {
- ApplicationContext context = new ClassPathXmlApplicationContext("chapter7/eg10/applicationContext.xml");
- TargetSource targetSource = (TargetSource) context.getBean("targetSource");
- for (int i = 0; i < 10; i++) {
- Apple apple = (Apple) targetSource.getTarget();
- apple.eat();
- }
- }
- }
執行結果如下:
- eat apple, id: 1
- eat apple, id: 1
- eat apple, id: 2
- eat apple, id: 1
- eat apple, id: 1
- eat apple, id: 2
- eat apple, id: 1
- eat apple, id: 1
- eat apple, id: 1
- eat apple, id: 1
從執行結果來看,自定義TargetSource的random特性是實現了,只是這裏使用id爲1的Apple執行次數要多一些,這主要是由於多線程執行會更傾向於使用當前已經獲得鎖的線程執行鎖定代碼。