中介者模式

2019年11月11日08:45:25

中介者模式(mediator pattern)

定義

從前的日色變得慢

車,馬,郵件都慢

一生只夠愛一個人

中介者模式(mediator pattern),用一个中介對象來封裝一系列的對象交互。中介者使各對象不需要顯式地互相引用,從而使其耦合鬆散,而且可以獨立地改變它們的交互。————《設計模式:可復用面向對象軟件的基礎》

中介者模式是一種對象行為型模式。

從木心這首小詩中的“郵件”中,討論一下中介者模式。

很久很久以前,你和她住在一個很大很大的村子裏面,你住在村的東邊,她住在村的西邊。

那年你才十八,她也正值青春年華,正月十五元宵節,你賞燈之時,她回首處,你一見鍾情。

往後的日子里,你每天都到她家送情書。送了99天,你想這不是辦法,每天大半天浪費在路上,沒時間賺錢。於是你想了一個辦法,創辦郵局,每天替村東邊的人送信件給村西邊的人,一舉兩得。慢慢郵局越來越大,南邊的人通過郵局來給北邊的人送信件,你找了幾個夥計,從南到北,從北到南送信。

多年後,你富甲一方,也娶了當年的她。

“郵局”就是中介者模式中的中介者,“你”和“她”就是中介者中的同事。

圖示

中介者模式結構圖:

角色

從中介者模式結構圖中可知,有以下4個角色:

  • (1)抽象中介者:定義了中介者
  • (2)具體中介者:實現了抽象中介者的方法,它需要知道所有具體同事對象,並從具體同事對象接收消息,向具體同事對象發出命令。
  • (3)抽象同事類:定義同事類
  • (4)具體同事類:實現抽象同事類,每個具體同事對象只知道自己的行為,而不了解其他同事對象的情況,但它們都認識中介者。

代碼示例

這是一個悲傷的故事,住在村東邊的你通過郵局給村西邊的她表白,她說,她已經有男朋友了。

類圖:

抽象中介者角色:

public interface PostOffice {
    /**
     * 送信
     */
    void deliverLetters(String letters, String receiver);

    /**
     * 添加收信人
     */
    void addPeople(Villager villager);
}

具體中介者角色:

public class PostOfficeImpl implements PostOffice {
    /**
     * 收信人信息
     */
    private HashMap villagerMap = new HashMap<String, Villager>();

    @Override
    public void addPeople(Villager villager) {
        villagerMap.put(villager.getClass().getSimpleName(), villager);
    }

    @Override
    public void deliverLetters(String letters, String receiver) {
        System.out.println("=>收信:郵局收到要寄的信");
        Villager villager = (Villager) villagerMap.get(receiver);
        System.out.println("=>送信:拿出地址本查詢收信人地址是:" + villager.getAddress() + ",送信");
        System.out.println("=>收信人看信:");
        villager.receiveLetter(letters);
    }
}

抽象同事類角色:

public abstract class Villager {
    protected PostOffice postOffice;
    protected String address;

    Villager(PostOffice postOffice, String address) {
        this.postOffice = postOffice;
        this.address = address;
    }

    public void receiveLetter(String letter) {
        System.out.println(letter);
    }

    public void sendLetter(String letter, String receiver) {
        postOffice.deliverLetters(letter, receiver);
    }

    public String getAddress() {
        return address;
    }
}

具體同事類角色:

// 她
public class She extends Villager {

    She(PostOffice postOffice, String address) {
        super(postOffice, address);
    }
}
// 你
public class You extends Villager {
    public You(PostOffice postOffice, String address) {
        super(postOffice, address);
    }
}

中介者模式測試類:

public class MediatorPatternTest {
    public static void main(String[] args) {
        PostOffice postOffice = new PostOfficeImpl();
        She she = new She(postOffice, "村西邊");
        You you = new You(postOffice, "村東邊");

        postOffice.addPeople(she);
        postOffice.addPeople(you);

        you.sendLetter("正月十五,元宵之夜,一見傾心", "She");
        she.sendLetter("對不起,我已經有男朋友了", "You");
    }
}

測試結果:

使用場景

村子很大,人很多,關係很複雜:系統中存在很多對象,對象之間存在複雜的引用關係,產生的相互依賴關係結構混亂且難以理解,使得對象無法重用

人與人之間書信交流:對象間存在某種共性交互行為,用中介者封裝這種行為

在這個很大的村子裏面,每個人要給不同人的送信,這種關係成網狀結構,錯綜複雜。

加入郵局中介者之後,成星狀結構,每個人只和郵局有關係。

總結:系統中存在很多對象,對象間存在複雜的關係,在複雜的關係中存在共性交互行為,封裝共性交互行為就是中介者。

中介者模式很容易在系統中應用,也很容易在系統中無用。當系統出現了“多對多”交互複雜的對象群是,不要急於使用中介者模式,而要先反思你的系統在設計上是不是合理。

實例有:聯合國,聊天室等。

中介者模式與迪米特法則

中介者模式是應用迪米特法則的典型。

迪米特法則:只與你最直接的朋友交流(Only talk to you immediate friends.)參考

優點

  • 解耦:使同事類對象耦合性降低,可以獨立變化和復用同事類
  • 把對象如何協作進行了抽象,將中介作為一個獨立的概念並將其封裝在一個對象中,這樣關注的對象就從對象各自本身的行為轉移到它們之間的交互上來,也就是在一個更宏觀的角度看待系統。

缺點

  • 在具體中介者類中包含了同事之間的交互細節,可能會導致具體中介者類非常複雜,不利於維護,後期可能有牽一發而動全身的危險。

總結

中介者模式,用一个中介對象來封裝一系列的對象交互。中介者使各對象不需要顯式地互相引用,從而使其耦合鬆散,而且可以獨立地改變它們的交互。

2019年11月17日16:32:36

本站聲明:網站內容來源於博客園,如有侵權,請聯繫我們,我們將及時處理

【其他文章推薦】

※為什麼 USB CONNECTOR 是電子產業重要的元件?

網頁設計一頭霧水??該從何著手呢? 找到專業技術的網頁設計公司,幫您輕鬆架站!

※想要讓你的商品成為最夯、最多人討論的話題?網頁設計公司讓你強力曝光

※想知道最厲害的台北網頁設計公司推薦台中網頁設計公司推薦專業設計師”嚨底家”!!

Convolutional Sequence to Sequence Learning 論文筆記

目錄

簡介

寫這篇博客主要是為了進一步了解如何將CNN當作Encoder結構來使用,同時這篇論文也是必看的論文之一。該論文證明了使用CNN作為特徵抽取結構實現Seq2Seq,可以達到與 RNN 相接近甚至更好的效果,並且CNN的高并行能力能夠大大減少我們的模型訓練時間(本文對原文中不清晰的部分做了梳理,建議與原文搭配服用)

原文鏈接:

模型結構如下圖所示:

下面對模型的每個部分進行分塊介紹:

Position Embeddings

卷積網絡和Transformer一樣,不是類似於RNN的時序模型,因此需要加入位置編碼來體現詞與詞之間的位置關係

  • 樣本輸入的詞向量:\(w = (w_1, w_2, …, w_n)\)
  • 樣本位置編碼:\(p = (p_1, p_2, …, p_n)\)
  • 最終詞向量表徵:\(e = (w_1 + p_1, w_2 + p_2, …, w_n + p_n)\)

GLU or GRU

GLU和GTU是在同一篇論文中提出的,其中,GLU也是CNN Seq2Seq的主要結構。可以直接將其當作激活函數來看待,其將某以卷積核的輸出輸入到兩個結構相同的卷積網絡,令其中一個的輸出為\(A\),另一個為\(B\)
GLU與GRU的區別就在於A輸出的激活函數不同:
\[GLU:H_0=A \otimes \sigma (B)\]

\[GTU:H_0=tanh(A) \otimes \sigma (B)\]

而CNN Seq2Seq就採用了GLU作為模型的激活函數

原文鏈接:

Convolutional Block Structure

編碼器與解碼器都是由多個卷積層構成的(原文中稱為block,實際上就是layer),每一層包含一個1維卷積核以及一個門控線性單元(Gated linear units, GLU)。假設單詞數即輸入長度為\(m\),kernel大小為\(k\),pad為\(p\),那麼計算輸出sequence長度的公式為\((m+2p-k)/stride+1\),只要適當的設置卷積核的kernel大小、pad以及步長參數,即可使得輸出序列與輸入序列的維度保持一致。在文中,輸入為25,kernel為5,則輸出序列長度為\((25+2*2-5)/1+1=25\)

另外,為了充分讓輸出節點跟整個sequence單詞有聯繫,必須使用多個卷積層,這樣才能使得最後一個卷積核有足夠大得感受野以感受整個句子的特徵,同時也能捕捉局部句子的特徵。

來看一下整個編碼器的前向傳播方式:

  • 每次輸入到卷積核的句子的大小為\(X \in R^{k\times d}\),表明每次卷積核能夠讀取的序列長度為\(k\),也就是卷積核的寬度為\(k\),詞向量維度為\(d\)
  • 卷積核的權重矩陣大小為\(W^{2d \times k \times d}\),偏置向量為\(b_W \in R^{2d}\),表明每一層有\(2d\)個卷積核,因此輸出序列的維度為\(2d\),而由於事先的設計,使得輸入序列與輸出序列的長度是相同的,因此經過卷積之後,得到的序列的矩陣大小為\(Y \in R^{k \times 2d}\)
  • 我們將上面的\(2d\)個卷積核分為兩個部分,這兩個部分的卷積核尺寸與個數完全相同,輸出維度也完全相同,則可以將其當作\(GLU\)的兩個輸入,輸入到GLU整合過後,輸出的序列維度又變為了\(\hat{Y} \in R^{k \times d}\)
  • 為了能夠實現深層次的網絡,在每一層的輸入和輸出之間採用了殘差結構
  • 對於解碼序列來說,我們需要提取解碼序列的隱藏表徵,但是解碼序列的解碼過程是時序遞歸的,即我們無法觀測到當前預測對象之後的序列,因此論文作者將輸入的decoder序列

這樣的卷積策略保證了每一層的輸入與輸出序列的一一對應,並且能夠將其看作簡單的編碼器單元,多層堆疊以實現更深層次的編碼。

Multi-step Attention

對於Attention的計算,關鍵就是找到 Query、Key 和 Value。下圖為計算Attention且解碼的示意圖

Attention的計算過程如下:

  • Query由decoder的最後一個卷積層的輸出\(h_i^l\)以及上一時刻decoder最終的生成的目標\(g_i\)共同決定,\(W^l_d\)\(b_d^l\)為線性映射的參數。
    \[d_i^l = W^l_dh^l_i+b_d^l+g_i\]

  • Key 則採用 Encoder 的輸出\(z_j^u\),典型的二維匹配模型,將 Query 與 Key 一一對齊,計算 dot attention分數:
    \[a_{ij}^l = \frac{exp(d^l_i \cdot z^u_j)}{\sum_{t=1}^mexp(z_j^u+e_j)}\]

  • Value 的值則取編碼器的輸出\(z_j^u\)以及詞向量表徵\(e_j\)之和,目的是為編碼器的輸出加上位置表徵信息。得到對應的 Value 值 \(c_i^l\) 之後,直接與當前時刻的 Decoder 輸出 \(h_i^l\) 相加,再輸入分類器進行分類。
    \[c_i^l = \sum_{j=1}^ma_{ij}^l(z_j^u + e_j)\]

Normalization Strategy

模型還通過歸一化策略來保證通過每一層模型的方差變化不會太大,這裏先簡單的記錄一下,具體的操作細節需要回去仔細琢磨代碼。歸一化的主要策略如下:

  • 對殘差網絡的輸入和輸出乘以 \(\sqrt{0.5}\) 來保證輸入和輸出的方差減半(這假設兩側的方差是相等的,雖然這不是總是正確的,但是實驗證明這樣做是有效的)
  • 由於注意力模塊的輸出向量為 m 個向量的加權和,因此將其乘以 \(m \sqrt{m}\) 來抵消方差的變化,其中,乘以 \(m\) 是為了將向量放大到原始的大小(實際中通常不會這麼做,但是這麼做的效果良好)
  • 由於採用了多重注意力機制的卷積解碼器,作者根據注意力機制的數量來對反向傳播到編碼器的梯度進行壓縮,這可以避免編碼器接收過多的梯度信息,使得訓練變得更加平穩。

Initialization

初始化的目的與歸一化是一致的,即都是為了保證前向與後項傳播的數據方差能夠保持在一個較穩定的水準,模型初始化的策略如下:

  • 此前如層都由平均值為0以及標準差為0.1的正太分佈進行初始化。
  • 對於其輸出未直接輸入門控線性單元的層,我們以正態分佈 \(N(0, \sqrt{1/n_l})\) 來初始化權重,其中 \(n_l\) 是每個神經元的輸入連接個數。 這樣可以確保正太分佈的輸入的方差得以保留
  • 對於輸出與GLU相連的層,我們採取不同的策略。如果GLU的輸入的均值為0且方差足夠小,則輸出方差可以近似等於輸入方差的1/4。 因此,需要初始化權重使得GLU激活的輸入具有該層輸入方差的4倍,即該層的初始化分佈為 \(N(0, \sqrt{4/n_l})\)
  • 此外,每一層的偏置 \(b\) 統一設置為0
  • 另外,考慮到 dropout 也會影響數據的方差分佈,假設dropout的保留概率為p,則方差將放大為 \(1/p\) 倍,因此上述提到的初始化策略需要修正為: \(N(0, \sqrt{p/n_l})\) 以及 \(N(0, \sqrt{4p/n_l})\)

最後的實驗部分就不記錄了,有興趣的同學可以去原文里看看。

本站聲明:網站內容來源於博客園,如有侵權,請聯繫我們,我們將及時處理

【其他文章推薦】

USB CONNECTOR掌控什麼技術要點? 帶您認識其相關發展及效能

※評比前十大台北網頁設計台北網站設計公司知名案例作品心得分享

※智慧手機時代的來臨,RWD網頁設計已成為網頁設計推薦首選

※評比南投搬家公司費用收費行情懶人包大公開

Spring源碼解析之@Configuration

@Configuration簡介

用於標識一個類為配置類,與xml配置效果類似

用法簡介

public class TestApplication {

    public static void main(String args[]) {
        AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(AppConfig.class);

    }
}

@Configuration
public class AppConfig {

    @Bean
    public A a(){
        return new A();
    }
    @Bean
    public B b(){
        return new B();
    }
} 




public class A {

    public A(){
        System.out.println("Call A constructor");
    }
}



public class B {

    public B(){
        System.out.println("Call B constructor");
    }
}

上面的例子應該是@Configuration最普遍一種使用場景了,在@Configuration class下面配置@Bean method,用於想Spring Ioc容器注入bean.但其實我們把AppConfig的@Configuration註解去掉,對應的Bean也是可以被注入到容器中去的。

那麼問題來了@Configuration到底有什麼作用?

我們給AppConfig改寫一下,如下:

@Configuration
@EnableAspectJAutoProxy
public class AppConfig {

   @Bean
   public A a(){
      b();
      return new A();
   }
   @Bean
   public B b(){
      return new B();
   }

再去執行TestApplication#main,那麼執行結果會是什麼樣呢?

Call A constructor
Call B constructor

嗯哼?按照Java的語法,B的構造函數應該是被調用了兩次啊?為什麼只有輸出一句Call B constructor?

這其實就是@Configuration再發揮作用啦,不信你去掉@Configuration,再去運行一下,就會發現B的構造函數被執行了兩次。

官方給出了這樣一段解釋對於被@Configuration註解的類

In common scenarios,@Beanmethods are to be declared within@Configurationclasses, ensuring that “full” mode is always used and that cross-method references therefore get redirected to the container’s lifecycle management.

在一般情況下,@Bean method 是被聲明在@Configuration類中的,以確保 full mode總是被使用,並且跨方法的引用會被重定向到容器生命周期管理。

怎麼理解呢?

原來Spring將被@Configuration註解的配置類定義為full configuration, 而將沒有被@Configuration註解的配置類定義為lite configuration。full configuration能重定向從跨方法的引用,從而保證上述代碼中的b bean是一個單例.

源碼中是如何實現@Configuration語意

public AnnotationConfigApplicationContext(Class<?>... componentClasses) {
   /**
    * 調用無參構造函數,實例化AnnotatedBeanDefinitionReader和ClassPathBeanDefinitionScanner
    * 同時會調用父類GenericApplicationContext無參構造函數實例化一個關鍵的工廠DefaultListableBeanFactory
    * 同時還會註冊一些開天闢地的後置處理器到beanDefinitionMap,這些後置處理器有bean工廠後置處理器;有bean後置處理器
    */
   this();
   //將componentClasses註冊到beanDefinitionMap集合中去
   register(componentClasses);
  
   refresh();
}

跟蹤refresh()

@Override
public void refresh() throws BeansException, IllegalStateException {
   synchronized (this.startupShutdownMonitor) {
      // Prepare this context for refreshing.
      prepareRefresh();

      // Tell the subclass to refresh the internal bean factory.
      ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

      // Prepare the bean factory for use in this context.
      prepareBeanFactory(beanFactory);

      try {
         // Allows post-processing of the bean factory in context subclasses.
         //供上下文(Context)子類繼承,允許在這裏後置處理bean factory
         postProcessBeanFactory(beanFactory);

         // Invoke factory processors registered as beans in the context.
         //按順序調用BeanFactoryPostProcessor,這裏的按順序僅實現了PriorityOrdered和Ordered的語意,未實現@Order註解的語意
         //通過調用ConfigurationConfigPostProcessor#postProcessBeanDefinitionRegistry
         //解析@Configuration配置類,將自定義的BeanFactoryPostProcessor、BeanPostProcessor註冊到beanDefinitionMap
         //接着實例化所有(包括開天闢地)的BeanFactoryPostProcessor,然後再調用BeanFactoryPostProcessor#postProcessBeanFactory
         invokeBeanFactoryPostProcessors(beanFactory);

         // Register bean processors that intercept bean creation.
         //按順序將BeanPostProcessor實例化成bean並註冊到beanFactory的beanPostProcessors,
         //這裏的按順序僅實現了PriorityOrdered和Ordered的語意,未實現@Order註解的語意
         //因為BeanPostProcessor要在普通bean初始化()前後被調用,所以需要提前完成實例化並註冊到beanFactory的beanPostProcessors
         registerBeanPostProcessors(beanFactory);

         // Initialize message source for this context.
         //註冊國際化相關的Bean
         initMessageSource();

         // Initialize event multicaster for this context.
         //為上下文註冊應用事件廣播器(用於ApplicationEvent的廣播),如果有自定義則使用自定義的,如果沒有則內部實例化一個
         initApplicationEventMulticaster();

         // Initialize other special beans in specific context subclasses.
         onRefresh();

         // Check for listener beans and register them.
         //註冊所有(靜態、動態)的listener,並廣播earlyApplicationEvents
         registerListeners();

         // Instantiate all remaining (non-lazy-init) singletons.
         //實例化用戶自定義的普通單例Bean(非開天闢地的、非後置處理器)
         finishBeanFactoryInitialization(beanFactory);

         // Last step: publish corresponding event.
         finishRefresh();
      }

      catch (BeansException ex) {
         if (logger.isWarnEnabled()) {
            logger.warn("Exception encountered during context initialization - " +
                  "cancelling refresh attempt: " + ex);
         }

         // Destroy already created singletons to avoid dangling resources.
         destroyBeans();

         // Reset 'active' flag.
         cancelRefresh(ex);

         // Propagate exception to caller.
         throw ex;
      }

      finally {
         // Reset common introspection caches in Spring's core, since we
         // might not ever need metadata for singleton beans anymore...
         resetCommonCaches();
      }
   }
}

跟蹤invokeBeanFactoryPostProcessors(beanFactory)

protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
   PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());

   // Detect a LoadTimeWeaver and prepare for weaving, if found in the meantime
   // (e.g. through an @Bean method registered by ConfigurationClassPostProcessor)
   if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
      beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
      beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
   }
}

跟蹤invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());

public static void invokeBeanFactoryPostProcessors(
            ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {

        // Invoke BeanDefinitionRegistryPostProcessors first, if any.
        Set<String> processedBeans = new HashSet<>();

        if (beanFactory instanceof BeanDefinitionRegistry) {
            BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
            List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
            List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();

            for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
                if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
                    BeanDefinitionRegistryPostProcessor registryProcessor =
                            (BeanDefinitionRegistryPostProcessor) postProcessor;
                    registryProcessor.postProcessBeanDefinitionRegistry(registry);
                    registryProcessors.add(registryProcessor);
                }
                else {
                    regularPostProcessors.add(postProcessor);
                }
            }

            // Do not initialize FactoryBeans here: We need to leave all regular beans
            // uninitialized to let the bean factory post-processors apply to them!
            // Separate between BeanDefinitionRegistryPostProcessors that implement
            // PriorityOrdered, Ordered, and the rest.
            List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();

            // First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
            String[] postProcessorNames =
                    beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
            for (String ppName : postProcessorNames) {
                if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
                    currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
                    processedBeans.add(ppName);
                }
            }
            sortPostProcessors(currentRegistryProcessors, beanFactory);
            registryProcessors.addAll(currentRegistryProcessors);
            //此處調用ConfigurationClassPostProcessor#postProcessBeanDefinitionRegistry,
            //解析配置類,為配置中的bean定義生成對應beanDefinition,並注入到registry的beanDefinitionMap
            invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
            currentRegistryProcessors.clear();

            // Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
            postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
            for (String ppName : postProcessorNames) {
                if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
                    currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
                    processedBeans.add(ppName);
                }
            }
            sortPostProcessors(currentRegistryProcessors, beanFactory);
            registryProcessors.addAll(currentRegistryProcessors);
            invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
            currentRegistryProcessors.clear();

            // Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
            boolean reiterate = true;
            while (reiterate) {
                reiterate = false;
                postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
                for (String ppName : postProcessorNames) {
                    if (!processedBeans.contains(ppName)) {
                        currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
                        processedBeans.add(ppName);
                        reiterate = true;
                    }
                }
                sortPostProcessors(currentRegistryProcessors, beanFactory);
                registryProcessors.addAll(currentRegistryProcessors);
                invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
                currentRegistryProcessors.clear();
            }

            // Now, invoke the postProcessBeanFactory callback of all processors handled so far.
            //調用ConfigurationClassPostProcessor#postProcessBeanFactory增強配置類(通過cglib生成增強類,load到jvm內存,
            //設置beanDefinition的beanClass為增強類)
            //為什麼要增強配置類?主要是為了讓@Bean生成的bean是單例,
            invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
            invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
        }

        else {
            // Invoke factory processors registered with the context instance.
            invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
        }

        // Do not initialize FactoryBeans here: We need to leave all regular beans
        // uninitialized to let the bean factory post-processors apply to them!
        String[] postProcessorNames =
                beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);

        // Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
        // Ordered, and the rest.
        List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
        List<String> orderedPostProcessorNames = new ArrayList<>();
        List<String> nonOrderedPostProcessorNames = new ArrayList<>();
        for (String ppName : postProcessorNames) {
            if (processedBeans.contains(ppName)) {
                // skip - already processed in first phase above
            }
            else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
                priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
            }
            else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
                orderedPostProcessorNames.add(ppName);
            }
            else {
                nonOrderedPostProcessorNames.add(ppName);
            }
        }

        // First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
        sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
        invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);

        // Next, invoke the BeanFactoryPostProcessors that implement Ordered.
        List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
        for (String postProcessorName : orderedPostProcessorNames) {
            orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
        }
        sortPostProcessors(orderedPostProcessors, beanFactory);
        invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);

        // Finally, invoke all other BeanFactoryPostProcessors.
        List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
        for (String postProcessorName : nonOrderedPostProcessorNames) {
            nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
        }
        invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);

        // Clear cached merged bean definitions since the post-processors might have
        // modified the original metadata, e.g. replacing placeholders in values...
        beanFactory.clearMetadataCache();
    }

跟蹤invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);

private static void invokeBeanFactoryPostProcessors(
      Collection<? extends BeanFactoryPostProcessor> postProcessors, ConfigurableListableBeanFactory beanFactory) {

   for (BeanFactoryPostProcessor postProcessor : postProcessors) {
      postProcessor.postProcessBeanFactory(beanFactory);
   }
}

跟蹤ConfigurationClassPostProcessor#postProcessBeanFactory

@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
   int factoryId = System.identityHashCode(beanFactory);
   if (this.factoriesPostProcessed.contains(factoryId)) {
      throw new IllegalStateException(
            "postProcessBeanFactory already called on this post-processor against " + beanFactory);
   }
   this.factoriesPostProcessed.add(factoryId);
   if (!this.registriesPostProcessed.contains(factoryId)) {
      // BeanDefinitionRegistryPostProcessor hook apparently not supported...
      // Simply call processConfigurationClasses lazily at this point then.
      processConfigBeanDefinitions((BeanDefinitionRegistry) beanFactory);
   }
   //為@Configuration註解的類生成增強類(如果有必要),並替換bd中的beanClass屬性,
   enhanceConfigurationClasses(beanFactory);
   beanFactory.addBeanPostProcessor(new ImportAwareBeanPostProcessor(beanFactory));
}

到了這一步謎底幾乎已經揭曉了,@Configuration class是通過增強來實現它的語義的。通過增強把跨方法的引用調用重定向到Spring生命周期管理.我們近一步探索下這個enhanceConfigurationClasses方法

public void enhanceConfigurationClasses(ConfigurableListableBeanFactory beanFactory) {
   Map<String, AbstractBeanDefinition> configBeanDefs = new LinkedHashMap<>();
   for (String beanName : beanFactory.getBeanDefinitionNames()) {
      BeanDefinition beanDef = beanFactory.getBeanDefinition(beanName);
      Object configClassAttr = beanDef.getAttribute(ConfigurationClassUtils.CONFIGURATION_CLASS_ATTRIBUTE);
      MethodMetadata methodMetadata = null;
      if (beanDef instanceof AnnotatedBeanDefinition) {
         methodMetadata = ((AnnotatedBeanDefinition) beanDef).getFactoryMethodMetadata();
      }
      if ((configClassAttr != null || methodMetadata != null) && beanDef instanceof AbstractBeanDefinition) {
         // Configuration class (full or lite) or a configuration-derived @Bean method
         // -> resolve bean class at this point...
         AbstractBeanDefinition abd = (AbstractBeanDefinition) beanDef;
         if (!abd.hasBeanClass()) {
            try {
               abd.resolveBeanClass(this.beanClassLoader);
            }
            catch (Throwable ex) {
               throw new IllegalStateException(
                     "Cannot load configuration class: " + beanDef.getBeanClassName(), ex);
            }
         }
      }
      //在ConfigurationClassUtils.checkConfigurationClassCandidate方法中會標記Configuration is full or lite
      if (ConfigurationClassUtils.CONFIGURATION_CLASS_FULL.equals(configClassAttr)) {
         if (!(beanDef instanceof AbstractBeanDefinition)) {
            throw new BeanDefinitionStoreException("Cannot enhance @Configuration bean definition '" +
                  beanName + "' since it is not stored in an AbstractBeanDefinition subclass");
         }
         else if (logger.isInfoEnabled() && beanFactory.containsSingleton(beanName)) {
            logger.info("Cannot enhance @Configuration bean definition '" + beanName +
                  "' since its singleton instance has been created too early. The typical cause " +
                  "is a non-static @Bean method with a BeanDefinitionRegistryPostProcessor " +
                  "return type: Consider declaring such methods as 'static'.");
         }
         configBeanDefs.put(beanName, (AbstractBeanDefinition) beanDef);
      }
   }
   if (configBeanDefs.isEmpty()) {
      // nothing to enhance -> return immediately
      return;
   }

   ConfigurationClassEnhancer enhancer = new ConfigurationClassEnhancer();
   for (Map.Entry<String, AbstractBeanDefinition> entry : configBeanDefs.entrySet()) {
      AbstractBeanDefinition beanDef = entry.getValue();
      // If a @Configuration class gets proxied, always proxy the target class
      beanDef.setAttribute(AutoProxyUtils.PRESERVE_TARGET_CLASS_ATTRIBUTE, Boolean.TRUE);
      // Set enhanced subclass of the user-specified bean class
      Class<?> configClass = beanDef.getBeanClass();
      //為@Configuration註解的類生成增強類
      Class<?> enhancedClass = enhancer.enhance(configClass, this.beanClassLoader);
      if (configClass != enhancedClass) {
         if (logger.isTraceEnabled()) {
            logger.trace(String.format("Replacing bean definition '%s' existing class '%s' with " +
                  "enhanced class '%s'", entry.getKey(), configClass.getName(), enhancedClass.getName()));
         }
         beanDef.setBeanClass(enhancedClass);
      }
   }
}

看到有那麼一句話Class<?> enhancedClass = enhancer.enhance(configClass, this.beanClassLoader);

很明顯了,使用cglib技術為config class生成一個enhancedClass,再通過beanDef.setBeanClass(enhancedClass);修改beanDefinition的BeanClass屬性,在bean實例化階段,會利用反射技術將beanClass屬性對應的類實例化出來,所以最終實例化出來的@Configuration bean是一個代理類的實例。這裏稍微提一下為什麼要使用cglib,而不是jdk動態代理,主要是因為jdk動態代理是基於接口的,而這裏AppConfig並沒有實現任何接口,所以必須用cglib技術。

總結

被@Configuration 註解的類,是 full configuration class,該類會被增強(通過cglib),從而實現跨方法引用調用被重定向到Spring 生命周期管理,最終保證@Bean method生成的bean是一個單例。

本站聲明:網站內容來源於博客園,如有侵權,請聯繫我們,我們將及時處理

【其他文章推薦】

台北網頁設計公司這麼多,該如何挑選?? 網頁設計報價省錢懶人包"嚨底家"

網頁設計公司推薦更多不同的設計風格,搶佔消費者視覺第一線

※想知道購買電動車哪裡補助最多?台中電動車補助資訊懶人包彙整

南投搬家費用,距離,噸數怎麼算?達人教你簡易估價知識!

做程序員的一些偏見

“人類的心靈有一種神奇的能力,它能夠感知到別人的虛情假意。如果銷售人員的暗示是一種虛情假意的產物,那麼幾乎刻意肯定的是,這種暗示在客戶心中產生的結果也不會是一種真實的情感。”

                                                                ——諾瓦爾·霍金斯

前天,銷售同事老吳還說,做銷售一定要講人品,而且做人很重要。我很贊同他的觀點,但我還是對他的觀點做了補充:不單單是銷售要學會做人,我們任何一個崗位、任何一個人都要學會如何做人。崗位是做事層面,做人是做事的根基,無論你是銷售還是程序員、都離不開做人。我在部門裡經常對同事們說,甚至在面試的時候也跟應聘者強調,我們都是全民銷售。因為我們扁平化的開放管理制度,我們任何一個員工都有可能直接面對客戶。作為服務行業的我們,任何一個同事的印象以及專業態度都是我們的招牌。面對客戶就是面對市場,面對市場的員工就是覆蓋了銷售的角色。我們每個人都代表着一個企業,更代表了自己。有些客戶可能因為我們需求做得好,所以給了我更多的機會;也有可能有些客戶因為我們的美工同事洞悉到了客戶的需求而用真誠的設計打動了客戶,贏下了訂單;甚至可能是我們善良、踏實、勤奮的程序員同事感動了客戶,非要跟我們合作不可。這裏都包含着公司的文化和個人的修養。

 

我過去一直深受着各種流言的毒害,當然,我不會把問題丟給環境,真正的問題在於自己沒有足夠的獨立思考和判斷能力。別人說程序員普遍悶騷,別人說美工都很藝術,還有人說需求就是要有足夠的健談和洞察能力。其實,話有時候並沒有毛病,但我們缺少一個宏觀與高度的視野能力會很容易讓自己“入戲”,也就是會以偏概全。就像同事老吳說銷售考驗做人,如果我弱一點,我真會以為作為程序員的自己就沒那麼需要關注做人層面了,反正自己不用天天面對客戶。這就是我們常說的短見。

 

我現在的職位寫着是部門經理,不止戰略,在戰術上如架構、設計、開發我都一直在做,還帶着近80號人。我目前的狀態不是因為我踩正了職業規劃路線,或者我有管理的能力。而是我看不過眼和忍受不了之前團隊的低效和散漫,想自己做得有成就一點,有效率一點而已。沒人敢這麼做,而領導敢給我這樣一個機會,那就只有我自己扛起大旗向前沖了。有時候,當自己真覺得環境待不下去了,可能就是自己的機會。我不知道自己有沒有這個能力,但我有一個看清問題本質的視野和敢說敢做勇氣。個人發展的本質並不是職位驅動的,任何一個有能力的人都能有機會上升,不管你是美工、測試、需求還是程序員,就看自己願不願意放開自己思維和勇氣。我很早就已經說過,職位在做事面前都是一文不值。千萬不要被各種所謂的管理晉陞路線和技術大咖晉陞路線給誤導。人生都是問題驅動的,每個人的起點都不一樣,問題也都不一樣。多把視野放在當前問題身上,而不是帶着別人給出的規劃建議去逃避自己當前的問題,這個同事不好,那個老闆不行,這都不是自己想要的,這都是借口。能讓自己過得好,能讓家人過得好才是王道。所以,從這個角度看,無論什麼職位,跑得越高,越是辛苦。認識不了這個本質的,永遠做不了高層。

 

我們一出生就已經內置了銷售這個職位,我們需要與人打交道,我們需要結交朋友,我們需要面試找工作等等。其實,我們無時無刻在銷售着自己。而真誠就是我們每一個都需要具備的銷售品質。做銷售的門檻很低,可是考驗很大,但前途也無可限量。

本站聲明:網站內容來源於博客園,如有侵權,請聯繫我們,我們將及時處理

【其他文章推薦】

※想知道網站建置網站改版該如何進行嗎?將由專業工程師為您規劃客製化網頁設計後台網頁設計

※不管是台北網頁設計公司台中網頁設計公司,全省皆有專員為您服務

※Google地圖已可更新顯示潭子電動車充電站設置地點!!

※帶您來看台北網站建置台北網頁設計,各種案例分享

02-MyBatis執行Sql的流程分析

目錄

本博客着重介紹MyBatis執行Sql的流程,關於在執行過程中緩存、動態SQl生成等細節不在本博客中體現,相應內容後面再單獨寫博客分析吧。

還是以之前的查詢作為列子:

public class UserDaoTest {

    private SqlSessionFactory sqlSessionFactory;

    @Before
    public void setUp() throws Exception{
        ClassPathResource resource = new ClassPathResource("mybatis-config.xml");
        InputStream inputStream = resource.getInputStream();
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    }

    @Test
    public void selectUserTest(){
        String id = "{0003CCCA-AEA9-4A1E-A3CC-06D884BA3906}";
        SqlSession sqlSession = sqlSessionFactory.openSession();
        CbondissuerMapper cbondissuerMapper = sqlSession.getMapper(CbondissuerMapper.class);
        Cbondissuer cbondissuer = cbondissuerMapper.selectByPrimaryKey(id);
        System.out.println(cbondissuer);
        sqlSession.close();
    }

}

之前提到拿到sqlSession之後就能進行各種CRUD操作了,所以我們就從sqlSession.getMapper這個方法開始分析,看下整個Sql的執行流程是怎麼樣的。

獲取Mapper

進入sqlSession.getMapper方法,會發現調的是Configration對象的getMapper方法:

public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
    //mapperRegistry實質上是一個Map,裏面註冊了啟動過程中解析的各種Mapper.xml
    //mapperRegistry的key是接口的全限定名,比如com.csx.demo.spring.boot.dao.SysUserMapper
    //mapperRegistry的Value是MapperProxyFactory,用於生成對應的MapperProxy(動態代理類)
    return mapperRegistry.getMapper(type, sqlSession);
}

進入getMapper方法:

public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
    final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type);
    //如果配置文件中沒有配置相關Mapper,直接拋異常
    if (mapperProxyFactory == null) {
      throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
    }
    try {
      //關鍵方法
      return mapperProxyFactory.newInstance(sqlSession);
    } catch (Exception e) {
      throw new BindingException("Error getting mapper instance. Cause: " + e, e);
    }
  }

進入MapperProxyFactory的newInstance方法:

public class MapperProxyFactory<T> {

  private final Class<T> mapperInterface;
  private final Map<Method, MapperMethod> methodCache = new ConcurrentHashMap<Method, MapperMethod>();

  public MapperProxyFactory(Class<T> mapperInterface) {
    this.mapperInterface = mapperInterface;
  }

  public Class<T> getMapperInterface() {
    return mapperInterface;
  }

  public Map<Method, MapperMethod> getMethodCache() {
    return methodCache;
  }

  //生成Mapper接口的動態代理類MapperProxy
  @SuppressWarnings("unchecked")
  protected T newInstance(MapperProxy<T> mapperProxy) {
    return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
  }
  
  public T newInstance(SqlSession sqlSession) {
    final MapperProxy<T> mapperProxy = new MapperProxy<T>(sqlSession, mapperInterface, methodCache);
    return newInstance(mapperProxy);
  }

}

下面是動態代理類MapperProxy,調用Mapper接口的所有方法都會先調用到這個代理類的invoke方法(注意由於Mybatis中的Mapper接口沒有實現類,所以MapperProxy這個代理對象中沒有委託類,也就是說MapperProxy幹了代理類和委託類的事情)。好了下面重點看下invoke方法。

//MapperProxy代理類
public class MapperProxy<T> implements InvocationHandler, Serializable {

  private static final long serialVersionUID = -6424540398559729838L;
  private final SqlSession sqlSession;
  private final Class<T> mapperInterface;
  private final Map<Method, MapperMethod> methodCache;

  public MapperProxy(SqlSession sqlSession, Class<T> mapperInterface, Map<Method, MapperMethod> methodCache) {
    this.sqlSession = sqlSession;
    this.mapperInterface = mapperInterface;
    this.methodCache = methodCache;
  }

  @Override
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    try {
      if (Object.class.equals(method.getDeclaringClass())) {
        return method.invoke(this, args);
      } else if (isDefaultMethod(method)) {
        return invokeDefaultMethod(proxy, method, args);
      }
    } catch (Throwable t) {
      throw ExceptionUtil.unwrapThrowable(t);
    }
    //獲取MapperMethod,並調用MapperMethod
    final MapperMethod mapperMethod = cachedMapperMethod(method);
    return mapperMethod.execute(sqlSession, args);
  }

  private MapperMethod cachedMapperMethod(Method method) {
    MapperMethod mapperMethod = methodCache.get(method);
    if (mapperMethod == null) {
      mapperMethod = new MapperMethod(mapperInterface, method, sqlSession.getConfiguration());
      methodCache.put(method, mapperMethod);
    }
    return mapperMethod;
  }

  @UsesJava7
  private Object invokeDefaultMethod(Object proxy, Method method, Object[] args)
      throws Throwable {
    final Constructor<MethodHandles.Lookup> constructor = MethodHandles.Lookup.class
        .getDeclaredConstructor(Class.class, int.class);
    if (!constructor.isAccessible()) {
      constructor.setAccessible(true);
    }
    final Class<?> declaringClass = method.getDeclaringClass();
    return constructor
        .newInstance(declaringClass,
            MethodHandles.Lookup.PRIVATE | MethodHandles.Lookup.PROTECTED
                | MethodHandles.Lookup.PACKAGE | MethodHandles.Lookup.PUBLIC)
        .unreflectSpecial(method, declaringClass).bindTo(proxy).invokeWithArguments(args);
  }

  /**
   * Backport of java.lang.reflect.Method#isDefault()
   */
  private boolean isDefaultMethod(Method method) {
    return ((method.getModifiers()
        & (Modifier.ABSTRACT | Modifier.PUBLIC | Modifier.STATIC)) == Modifier.PUBLIC)
        && method.getDeclaringClass().isInterface();
  }
}

所以這邊需要進入MapperMethod的execute方法:

public Object execute(SqlSession sqlSession, Object[] args) {
    Object result;
    //判斷是CRUD那種方法
    switch (command.getType()) {
      case INSERT: {
        Object param = method.convertArgsToSqlCommandParam(args);
        result = rowCountResult(sqlSession.insert(command.getName(), param));
        break;
      }
      case UPDATE: {
        Object param = method.convertArgsToSqlCommandParam(args);
        result = rowCountResult(sqlSession.update(command.getName(), param));
        break;
      }
      case DELETE: {
        Object param = method.convertArgsToSqlCommandParam(args);
        result = rowCountResult(sqlSession.delete(command.getName(), param));
        break;
      }
      case SELECT:
        if (method.returnsVoid() && method.hasResultHandler()) {
          executeWithResultHandler(sqlSession, args);
          result = null;
        } else if (method.returnsMany()) {
          result = executeForMany(sqlSession, args);
        } else if (method.returnsMap()) {
          result = executeForMap(sqlSession, args);
        } else if (method.returnsCursor()) {
          result = executeForCursor(sqlSession, args);
        } else {
          Object param = method.convertArgsToSqlCommandParam(args);
          result = sqlSession.selectOne(command.getName(), param);
        }
        break;
      case FLUSH:
        result = sqlSession.flushStatements();
        break;
      default:
        throw new BindingException("Unknown execution method for: " + command.getName());
    }
    if (result == null && method.getReturnType().isPrimitive() && !method.returnsVoid()) {
      throw new BindingException("Mapper method '" + command.getName() 
          + " attempted to return null from a method with a primitive return type (" + method.getReturnType() + ").");
    }
    return result;
  }

然後,通過一層一層的調用,最終會來到doQuery方法, 這兒咱們就隨便找個Excutor看看doQuery方法的實現吧,我這兒選擇了SimpleExecutor:

public <E> List<E> doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
    Statement stmt = null;
    try {
      Configuration configuration = ms.getConfiguration();
      //內部封裝了ParameterHandler和ResultSetHandler
      StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);
      stmt = prepareStatement(handler, ms.getStatementLog());
      //StatementHandler封裝了Statement, 讓 StatementHandler 去處理
      return handler.<E>query(stmt, resultHandler);
    } finally {
      closeStatement(stmt);
    }
  }

接下來,咱們看看StatementHandler 的一個實現類 PreparedStatementHandler(這也是我們最常用的,封裝的是PreparedStatement), 看看它使怎麼去處理的:

public <E> List<E> query(Statement statement, ResultHandler resultHandler) throws SQLException {
     //到此,原形畢露, PreparedStatement, 這個大家都已經滾瓜爛熟了吧
    PreparedStatement ps = (PreparedStatement) statement;
    ps.execute();
    //結果交給了ResultSetHandler 去處理,處理完之後返回給客戶端
    return resultSetHandler.<E> handleResultSets(ps);
  }

到此,整個調用流程結束。

簡單總結

這邊結合獲取SqlSession的流程,做下簡單的總結:

  • SqlSessionFactoryBuilder解析配置文件,包括屬性配置、別名配置、攔截器配置、環境(數據源和事務管理器)、Mapper配置等;解析完這些配置後會生成一個Configration對象,這個對象中包含了MyBatis需要的所有配置,然後會用這個Configration對象創建一個SqlSessionFactory對象,這個對象中包含了Configration對象;
  • 拿到SqlSessionFactory對象后,會調用SqlSessionFactory的openSesison方法,這個方法會創建一個Sql執行器(Executor組件中包含了Transaction對象),這個Sql執行器會代理你配置的攔截器方法
  • 獲得上面的Sql執行器后,會創建一個SqlSession(默認使用DefaultSqlSession),這個SqlSession中也包含了Configration對象和上面創建的Executor對象,所以通過SqlSession也能拿到全局配置;
  • 獲得SqlSession對象后就能執行各種CRUD方法了。

以上是獲得SqlSession的流程,下面總結下本博客中介紹的Sql的執行流程:

  • 調用SqlSession的getMapper方法,獲得Mapper接口的動態代理對象MapperProxy,調用Mapper接口的所有方法都會調用到MapperProxy的invoke方法(動態代理機制);
  • MapperProxy的invoke方法中唯一做的就是創建一個MapperMethod對象,然後調用這個對象的execute方法,sqlSession會作為execute方法的入參;
  • 往下,層層調下來會進入Executor組件(如果配置插件會對Executor進行動態代理)的query方法,這個方法中會創建一個StatementHandler對象,這個對象中同時會封裝ParameterHandler和ResultSetHandler對象。調用StatementHandler預編譯參數以及設置參數值,使用ParameterHandler來給sql設置參數。

Executor組件有兩個直接實現類,分別是BaseExecutor和CachingExecutor。CachingExecutor靜態代理了BaseExecutor。Executor組件封裝了Transction組件,Transction組件中又分裝了Datasource組件。

  • 調用StatementHandler的增刪改查方法獲得結果,ResultSetHandler對結果進行封裝轉換,請求結束。

Executor、StatementHandler 、ParameterHandler、ResultSetHandler,Mybatis的插件會對上面的四個組件進行動態代理。

重要類

  • MapperProxyFactory

  • MapperProxy

  • MapperMethod

  • SqlSession:作為MyBatis工作的主要頂層API,表示和數據庫交互的會話,完成必要數據庫增刪改查功能;

  • Executor:MyBatis執行器,是MyBatis 調度的核心,負責SQL語句的生成和查詢緩存的維護;

    StatementHandler 封裝了JDBC Statement操作,負責對JDBC statement 的操作,如設置參數、將Statement結果集轉換成List集合。
    ParameterHandler 負責對用戶傳遞的參數轉換成JDBC Statement 所需要的參數,
    ResultSetHandler 負責將JDBC返回的ResultSet結果集對象轉換成List類型的集合;
    TypeHandler 負責java數據類型和jdbc數據類型之間的映射和轉換
    MappedStatement MappedStatement維護了一條<select|update|delete|insert>節點的封裝,
    SqlSource 負責根據用戶傳遞的parameterObject,動態地生成SQL語句,將信息封裝到BoundSql對象中,並返回
    BoundSql 表示動態生成的SQL語句以及相應的參數信息

    Configuration MyBatis所有的配置信息都維持在Configuration對象之中。

參考

  • https://www.cnblogs.com/dongying/p/4031382.html
  • https://blog.csdn.net/qq_38409944/article/details/82494187

本站聲明:網站內容來源於博客園,如有侵權,請聯繫我們,我們將及時處理

【其他文章推薦】

網頁設計公司推薦更多不同的設計風格,搶佔消費者視覺第一線

※廣告預算用在刀口上,網站設計公司幫您達到更多曝光效益

※自行創業 缺乏曝光? 下一步"網站設計"幫您第一時間規劃公司的門面形象

南投搬家前需注意的眉眉角角,別等搬了再說!

(數據科學學習手札71)利用Python繪製詞雲圖

本文對應腳本及數據已上傳至我的Github倉庫

一、簡介

  詞雲圖是文本挖掘中用來表徵詞頻的數據可視化圖像,通過它可以很直觀地展現文本數據中地高頻詞:


圖1 詞雲圖示例

  在Python中有很多可視化框架可以用來製作詞雲圖,如,但這些框架並不是專門用於製作詞雲圖的,因此並不支持更加個性化的製圖需求,要想創作出更加美觀個性的詞雲圖,需要用到一些專門繪製詞雲圖的第三方模塊,本文就將針對其中較為優秀易用的以及的用法進行介紹和舉例說明。

二、利用wordcloud繪製詞雲圖

  wordcloud是Python中製作詞雲圖比較經典的一個模塊,賦予用戶高度的自由度來創作詞雲圖:


圖2 wordcloud製作詞雲圖示例

2.1 從一個簡單的例子開始

  這裏我們使用到來自wordcloud官方文檔中的constitution.txt來作為可視化的數據素材:


圖3 constitution.txt

  首先我們讀入數據並將數據清洗成空格分隔的長字符串:

import re

with open('constitution.txt') as c:
    '''抽取文本中的英文部分並小寫化,並將空格作為分隔拼接為長字符串'''
    text = ' '.join([word.group().lower() for word in re.finditer('[a-zA-Z]+', c.read())])

'''查看前100個字符'''
text[:500]

圖4 清洗后的片段文本

  接着使用wordcloud中用於生成詞雲圖的類WordCloud配合matplotlib,在默認參數設置下生成一張簡單的詞雲圖:

from wordcloud import WordCloud
import matplotlib.pyplot as plt
%matplotlib inline

'''從文本中生成詞雲圖'''
wordcloud = WordCloud().generate(text)
plt.figure(figsize=[12, 10])
plt.imshow(wordcloud)
plt.axis('off')
plt.show()

  生成的詞雲圖:


圖5 默認參數下的詞雲圖

  畢竟是在默認參數下生成的詞雲圖,既醜陋又模糊,為了繪製好看的詞雲圖,接下來我們來對wordcloud繪製詞雲圖的細節內容進行介紹,並不斷地對圖5進行升級改造。

2.2 WordCloud

  作為wordcloud繪製詞雲圖最核心的類,WordCloud的主要參數及說明如下:

font_path:字符型,用於傳入本地特定字體文件的路徑(ttf或otf文件)從而影響詞雲圖的字體族
width:int型,用於控制詞雲圖畫布寬度,默認為400
height:int型,用於控制詞雲圖畫布高度,默認為200
prefer_horizontal:float型,控制所有水平显示的文字相對於豎直显示文字的比例,越小則詞雲圖中豎直显示的文字越多
mask:傳入蒙版圖像矩陣,使得詞雲的分佈與傳入的蒙版圖像一致
contour:float型,當mask不為None時,contour參數決定了蒙版圖像輪廓線的显示寬度,默認為0即不显示輪廓線
contour_color:設置蒙版輪廓線的顏色,默認為’black’
scale:當畫布長寬固定時,按照比例進行放大畫布,如scale設置為1.5,則長和寬都是原來畫布的1.5倍
min_font_size:int型,控制詞雲圖中最小的詞對應的字體大小,默認為4
max_font_size:int型,控制詞雲圖中最大的詞對應的字體大小,默認為200
max_words:int型,控制一張畫布中最多繪製的詞個數,默認為200
stopwords:控制繪圖時忽略的停用詞,即不繪製停用詞中提及的詞,默認為None,即調用自帶的停用詞表(僅限英文,中文需自己提供並傳入)
background_color:控制詞雲圖背景色,默認為’black’
mode:當設置為’RGBA’且background_color設置為None時,背景色變為透明,默認為’RGB’
relative_scaling:float型,控制詞雲圖繪製字的字體大小與對應字詞頻的一致相關性,當設置為1時完全相關,當為0時完全不相關,默認為0.5
color_func:傳入自定義調色盤函數,默認為None
colormap:對應matplotlib中的colormap調色盤,默認為viridis,這個參數與參數color_func互斥,當color_func有函數傳入時本參數失效
repeat:bool型,控制是否允許一張詞雲圖中出現重複詞,默認為False即不允許重複詞
random_state:控制隨機數水平,傳入某個固定的数字之後每一次繪圖文字布局將不會改變

  了解了上述參數的意義之後,首先我們修改背景色為白色,增大圖床的長和寬,加大scale以提升圖片的精細程度,並使得水平显示的文字盡可能多:

'''從文本中生成詞雲圖'''
wordcloud = WordCloud(background_color='white', # 背景色為白色
                      height=400, # 高度設置為400
                      width=800, # 寬度設置為800
                      scale=20, # 長寬拉伸程度設置為20
                      prefer_horizontal=0.9999).generate(text)
plt.figure(figsize=[8, 4])
plt.imshow(wordcloud)
plt.axis('off')
'''保存到本地'''
plt.savefig('圖6.jpg', dpi=600, bbox_inches='tight', quality=95)
plt.show()

圖6

  可以看到相較於圖5,在美觀程度上有了很大的進步,接下來,我們在圖6的基礎上添加美國本土地圖蒙版:


圖7 美國本土地圖蒙版

  利用PIL模塊讀取我們的美國本土地圖蒙版.png文件並轉換為numpy數組,作為WordCloud的mask參數傳入:

from PIL import Image
import numpy as np

usa_mask = np.array(Image.open('美國本土地圖蒙版.png'))

'''從文本中生成詞雲圖'''
wordcloud = WordCloud(background_color='white', # 背景色為白色
                      height=4000, # 高度設置為400
                      width=8000, # 寬度設置為800
                      scale=20, # 長寬拉伸程度程度設置為20
                      prefer_horizontal=0.9999,
                      mask=usa_mask # 添加蒙版
                     ).generate(text)
plt.figure(figsize=[8, 4])
plt.imshow(wordcloud)
plt.axis('off')
'''保存到本地'''
plt.savefig('圖8.jpg', dpi=600, bbox_inches='tight', quality=95)
plt.show()

圖8

  可以看到圖8在圖6的基礎上進一步提升了美觀程度,接下來我們利用wordcloud中用於從圖片中提取調色方案的類ImageColorGenerator來從下面的星條旗美國地圖蒙版中提取色彩方案,進而反饋到詞雲圖上:


圖9 美國地圖蒙版_星條旗色

from PIL import Image
import numpy as np
from wordcloud import ImageColorGenerator

usa_mask = np.array(Image.open('美國地圖蒙版_星條旗色.png'))
image_colors = ImageColorGenerator(usa_mask)

'''從文本中生成詞雲圖'''
wordcloud = WordCloud(background_color='white', # 背景色為白色
                      height=400, # 高度設置為400
                      width=800, # 寬度設置為800
                      scale=20, # 長寬拉伸程度程度設置為20
                      prefer_horizontal=0.2, # 調整水平显示傾向程度為0.2
                      mask=usa_mask, # 添加蒙版
                      max_words=1000, # 設置最大显示字數為1000
                      relative_scaling=0.3, # 設置字體大小與詞頻的關聯程度為0.3
                      max_font_size=80 # 縮小最大字體為80
                     ).generate(text)

plt.figure(figsize=[8, 4])
plt.imshow(wordcloud.recolor(color_func=image_colors), alpha=1)
plt.axis('off')
'''保存到本地'''
plt.savefig('圖10.jpg', dpi=600, bbox_inches='tight', quality=95)
plt.show()

圖10

2.3 中文詞雲圖

  相較於英文文本語料,中文語料處理起來要麻煩一些,我們需要先進行分詞等預處理才能進行下一步的處理,這裏我們使用,先讀取進來看看:

import pandas as pd
import jieba

'''讀入原始數據'''
raw_comments = pd.read_csv('waimai_10k.csv');raw_comments.head()

圖11

  接下來我們利用rejieba以及pandas中的apply對評論列進行快速清洗:

'''導入停用詞表'''
with open('stopwords.txt') as s:
    stopwords = set([line.replace('\n', '') for line in s])

'''傳入apply的預處理函數,完成中文提取、分詞以及多餘空格剔除'''
def preprocessing(c):
    
    c = [word for word in jieba.cut(' '.join(re.findall('[\u4e00-\u9fa5]+', c))) if word != ' ' and word not in stopwords]

    return ' '.join(c)

'''將所有語料按空格拼接為一整段文字'''
comments = ' '.join(raw_comments['review'].apply(preprocessing));comments[:500]

  得到的結果如圖12:


圖12

  這時我們就得到所需的文本數據,接下來我們用美團外賣的logo圖片作為蒙版繪製詞雲圖:


圖13 美團外賣logo蒙版

from PIL import Image
import numpy as np
from wordcloud import ImageColorGenerator

waimai_mask = np.array(Image.open('美團外賣logo蒙版.png'))
image_colors = ImageColorGenerator(waimai_mask)

'''從文本中生成詞雲圖'''
wordcloud = WordCloud(background_color='white', # 背景色為白色
                      height=400, # 高度設置為400
                      width=800, # 寬度設置為800
                      scale=20, # 長寬拉伸程度程度設置為20
                      prefer_horizontal=0.2, # 調整水平显示傾向程度為0.2
                      mask=waimai_mask, # 添加蒙版
                      max_words=1000, # 設置最大显示字數為1000
                      relative_scaling=0.3, # 設置字體大小與詞頻的關聯程度為0.3
                      max_font_size=80 # 縮小最大字體為80
                     ).generate(comments)

plt.figure(figsize=[8, 4])
plt.imshow(wordcloud.recolor(color_func=image_colors), alpha=1)
plt.axis('off')
'''保存到本地'''
plt.savefig('圖14.jpg', dpi=600, bbox_inches='tight', quality=95)
plt.show()

  這時我們會發現詞雲圖上繪製出的全是亂碼,這是因為matplotlib默認字體是不包含中文的:


圖14 中文亂碼問題

  這時我們只需要為WordCloud傳入font_path參數即可,這裏我們選擇SimHei字體:

from PIL import Image
import numpy as np
from wordcloud import ImageColorGenerator

waimai_mask = np.array(Image.open('美團外賣logo蒙版.png'))
image_colors = ImageColorGenerator(waimai_mask)

'''從文本中生成詞雲圖'''
wordcloud = WordCloud(font_path='SimHei.ttf', # 定義SimHei字體文件
                      background_color='white', # 背景色為白色
                      height=400, # 高度設置為400
                      width=800, # 寬度設置為800
                      scale=20, # 長寬拉伸程度程度設置為20
                      prefer_horizontal=0.2, # 調整水平显示傾向程度為0.2
                      mask=waimai_mask, # 添加蒙版
                      max_words=1000, # 設置最大显示字數為1000
                      relative_scaling=0.3, # 設置字體大小與詞頻的關聯程度為0.3
                      max_font_size=80 # 縮小最大字體為80
                     ).generate(comments)

plt.figure(figsize=[8, 4])
plt.imshow(wordcloud.recolor(color_func=image_colors), alpha=1)
plt.axis('off')
'''保存到本地'''
plt.savefig('圖15.jpg', dpi=600, bbox_inches='tight', quality=95)
plt.show()

圖15

三、利用stylecloud繪製詞雲圖

  stylecloud是一個較為嶄新的模塊,它基於wordcloud,添加了一系列的嶄新特性譬如漸變顏色等,可以支持更為個性化的詞雲圖創作:


圖16 styleword製作詞雲圖示例

3.1 從一個簡單的例子開始

  這裏我們沿用上一章節中使用過的處理好的text來繪製詞雲圖:

import stylecloud
from IPython.display import Image # 用於在jupyter lab中显示本地圖片

'''生成詞雲圖'''
stylecloud.gen_stylecloud(text=text, 
                          size=512,
                          output_name='圖17.png')

'''显示本地圖片'''
Image(filename='圖17.png') 

圖17

  可以看出,styleword生成詞雲圖的方式跟wordcloud不同,它直接就將原始文本轉換成本地詞雲圖片文件,下面我們針對其繪製詞雲圖的細節內容進行介紹。

3.2 gen_stylecloud

  在stylecloud中繪製詞雲圖只需要gen_stylecloud這一個函數即可,其主要參數及說明如下:

text:字符串,格式同WordCloud中的generate()方法中傳入的text
gradient:控制詞雲圖顏色漸變的方向,’horizontal’表示水平方向上漸變,’vertical’表示豎直方向上漸變,默認為’horizontal’
size:控制輸出圖像文件的分辨率(因為stylecloud默認輸出方形圖片,所以size傳入的單個整數代表長和寬),默認為512
icon_name:這是stylecloud中的特殊參數,通過傳遞對應icon的名稱,你可以使用多達1544個免費圖標來作為詞雲圖的蒙版,點擊查看你可以免費使用的圖標蒙版樣式,默認為’fas fa-flag’
palette:控制調色方案,stylecloud的調色方案調用了,這是一個非常實用的模塊,其內部收集了數量驚人的大量的經典調色方案,默認為’cartocolors.qualitative.Bold_5′
background_color:字符串,控制詞雲圖底色,可傳入顏色名稱或16進制色彩,默認為’white’
max_font_size:同wordcloud
max_words:同wordcloud
stopwords:bool型,控制是否開啟去停用詞功能,默認為True,調用自帶的英文停用詞表
custom_stopwords:傳入自定義的停用詞List,配合stopwords共同使用
output_name:控制輸出詞雲圖文件的文件名,默認為stylecloud.png
font_path:傳入自定義字體*.ttf文件的路徑
random_state:同wordcloud

  對上述參數有所了解之後,下面我們在圖17的基礎上進行改良,首先我們將圖標形狀換成的樣子,接着將配色方案修改為:

'''生成詞雲圖'''
stylecloud.gen_stylecloud(text=text, 
                          size=1024,
                          output_name='圖18.png',
                          palette='scientific.diverging.Broc_3', # 設置配色方案
                          icon_name='fas fa-bomb' # 設置圖標樣式
                         )

'''显示本地圖片'''
Image(filename='圖18.png') 

圖18

3.3 繪製中文詞雲圖

  在wordcloud中繪製中文詞雲圖類似wordcloud只需要注意傳入支持中文的字體文件即可,下面我們使用一個微博語料數據weibo_senti_100k.csv來舉例:

weibo = pd.read_csv('weibo_senti_100k.csv')
weibo_text = [word for word in jieba.cut(' '.join(re.findall('[\u4e00-\u9fa5]+', ' '.join(weibo['review'].tolist())))) if word != ' ' and word not in stopwords]
weibo_text[:10]

圖19

  接着我們將蒙版圖標樣式換成,將色彩方案換成:

'''生成詞雲圖'''
stylecloud.gen_stylecloud(text=text, 
                          size=1024,
                          output_name='圖20.png',
                          palette='colorbrewer.sequential.Reds_3', # 設置配色方案為https://jiffyclub.github.io/palettable/colorbrewer/sequential/#reds_3
                          icon_name='fab fa-weibo', # 設置圖標樣式
                          gradient='horizontal', # 設置顏色漸變方向為水平
                          collocations=False # 不允許詞語重複显示
                         )

'''显示本地圖片'''
Image(filename='圖20.png') 

圖20

  以上就是本文的全部內容,如有筆誤望指出!

本站聲明:網站內容來源於博客園,如有侵權,請聯繫我們,我們將及時處理

【其他文章推薦】

※如何讓商品強力曝光呢? 網頁設計公司幫您建置最吸引人的網站,提高曝光率!!

網頁設計一頭霧水??該從何著手呢? 找到專業技術的網頁設計公司,幫您輕鬆架站!

※想知道最厲害的台北網頁設計公司推薦台中網頁設計公司推薦專業設計師”嚨底家”!!

印度研究:森林大火致黑碳更濃 加速冰河融化

摘錄自2020年2月4日中央通訊社報導

印度一項最新研究顯示,森林大火引發的黑碳(black carbon)濃度增加,加速冰河融化,更引發海平面升高及氣候變遷惡化。印度斯坦時報(Hindustan Times)今天(4日)引述WIHG科學家內基(PS Negi)指出,經過研究團隊過去幾年在北阿坎德省根戈催里冰河(Gangotri Glacier)鄰近地區的觀察與研究,森林大火導致黑碳濃度增加近一倍,加速了這條冰河的融化速度。

黑碳是一種懸浮粒子,源於石油、煤、木炭、樹木、柴草、塑膠垃圾、動物糞便等含碳物質燃燒不完全及氧化後所形成的產物。內基說,黑碳已公認是造成氣候變遷的第二重要人為因素。由於黑碳吸收更多光源且釋放紅外線輻射,從而提高當地溫度,導致冰河融化。當喜瑪拉雅山區高處的黑碳濃度增加時,使喜瑪拉雅山區的冰河融化更快。他認為,由於源自全球、區域和本地的開發及污染不斷累積,導致喜瑪拉雅山區的黑碳濃度增加,進而加速冰河融化,連帶影響全球氣候變遷。

至於森林大火的起因,根據印度森林調查報告(Forest Survey of India),北阿坎德省通常在2到6月通報森林火災,火災起因包括人為因素及閃電。根據官方統計,從2000年以來,北阿坎德省森林大火導致4萬4554公頃的森林遭到破壞。

本站聲明:網站內容來源環境資訊中心https://e-info.org.tw/,如有侵權,請聯繫我們,我們將及時處理

【其他文章推薦】

※如何讓商品強力曝光呢? 網頁設計公司幫您建置最吸引人的網站,提高曝光率!!

網頁設計一頭霧水??該從何著手呢? 找到專業技術的網頁設計公司,幫您輕鬆架站!

※想知道最厲害的台北網頁設計公司推薦台中網頁設計公司推薦專業設計師”嚨底家”!!

溫暖海水底下竄 格陵蘭冰川加快融化速度

摘錄自2020年2月4日中央通訊社報導

科學家早就知道氣溫上升會造成格陵蘭冰川表層融化,但最新研究發現,另一項威脅也從冰川下方展開:在格陵蘭巨大冰川底下流動的溫暖海水使融冰速度加快。

這項研究今天(3日)刊登在英國期刊「自然地球科學」(Nature Geoscience),參與調查的學者研究格陵蘭東北部一條被稱為「北緯79度冰川」的眾多「冰舌」 (ice tongue)之一。美國有線電視新聞網(CNN)報導,冰舌就是漂浮在水上卻沒跟陸地冰層脫離的冰條。這群科學家研究的這條巨大冰舌將近80公里長。這項新研究顯示,一股來自大西洋且超過1.6公里寬的溫暖海水,能直接流向這群學者研究的冰川,讓大量熱能接觸冰層,進而加速冰川融化。

格陵蘭大量融冰是現在全球海平面上升的最主要原因,那裡的融冰水量能讓全球海平面上升超過7.3公尺。丹麥氣象研究所氣候科學家莫特拉姆(Ruth Mottram)曾指出,光是去年7月,格陵蘭冰層就有1970億噸的冰消失,相當於8000萬個奧運泳池的水量。

本站聲明:網站內容來源環境資訊中心https://e-info.org.tw/,如有侵權,請聯繫我們,我們將及時處理

【其他文章推薦】

網頁設計公司推薦更多不同的設計風格,搶佔消費者視覺第一線

※廣告預算用在刀口上,網站設計公司幫您達到更多曝光效益

※自行創業 缺乏曝光? 下一步"網站設計"幫您第一時間規劃公司的門面形象

南投搬家前需注意的眉眉角角,別等搬了再說!

希臘擬建水上圍牆 恐增移民罹難機率

苦勞網2020年2月3日報導;陳韋綸編譯

為了阻止更多移民自土耳其前來,,此舉引發人道組織的抨擊,認為將增加庇護尋求者與難民途中遭遇的危險,反對派也稱計畫「愚蠢」,更不可能阻止移民。

希臘政府預計在愛琴海北部的勒斯博島(Lesbos)設置長達2.7公里的網狀屏障,屏障將高於海平面50公分,費用約為50萬歐元(約新台幣1,680萬元)。勒斯博島上的摩利亞(Moria)難民營,是希臘主要的難民接待中心,原本僅能容納3千人的難民營,如今卻擠滿1萬9千人,環境惡劣,。

「遊戲規則已經改變!」掌管移民與難民事務的部長米塔拉希斯(Notis Mitarakis)嚴詞宣告:希臘不是想來就來的地方,「我們將採取一切措施保護邊境」,甚至揚言將加速驅逐出境的流程。

去年共計7萬2千人抵達希臘,米塔拉希斯表示,今年1月起,只要不符合難民資格的人,幾個月內便會被遣返土耳其。對於一百多萬民因戰爭逃離敘利亞的難民而言,希臘是進入歐盟的閘門,與希臘僅有愛琴海之隔的土耳其,已收容4百多萬名敘利亞難民,人數是世界之最。

國際特赦組織(AI)批評,此計畫不但增加庇護尋求者與難民上岸的難度,也嚴重影響救援者的協助工作,要求政府採取必要的安全措施,確保這套系統不會造成更多人犧牲。,而且難以實現。「即便是孩子都知道,海上建牆是不可能的。」

※轉載自()

本站聲明:網站內容來源環境資訊中心https://e-info.org.tw/,如有侵權,請聯繫我們,我們將及時處理

【其他文章推薦】

※想知道網站建置網站改版該如何進行嗎?將由專業工程師為您規劃客製化網頁設計後台網頁設計

※不管是台北網頁設計公司台中網頁設計公司,全省皆有專員為您服務

※Google地圖已可更新顯示潭子電動車充電站設置地點!!

※帶您來看台北網站建置台北網頁設計,各種案例分享

海洋熱浪讓更多鯨魚受困漁網 專家將研發預測工具

環境資訊中心綜合外電;姜唯 編譯;林大利 審校

本站聲明:網站內容來源環境資訊中心https://e-info.org.tw/,如有侵權,請聯繫我們,我們將及時處理

【其他文章推薦】

台北網頁設計公司這麼多,該如何挑選?? 網頁設計報價省錢懶人包"嚨底家"

網頁設計公司推薦更多不同的設計風格,搶佔消費者視覺第一線

※想知道購買電動車哪裡補助最多?台中電動車補助資訊懶人包彙整

南投搬家費用,距離,噸數怎麼算?達人教你簡易估價知識!