最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Component和Configuration注解區(qū)別實例詳解

 更新時間:2022年11月03日 10:00:18   作者:AlvinYueChao  
這篇文章主要為大家介紹了Component和Configuration注解區(qū)別實例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪

引言

第一眼看到這個題目,我相信大家都會腦子里面彈出來一個想法:這不都是 Spring 的注解么,加了這兩個注解的類都會被最終封裝成 BeanDefinition 交給 Spring 管理,能有什么區(qū)別?

首先先給大家看一段示例代碼:

AnnotationBean.java

import lombok.Data;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
@Component
//@Configuration
public class AnnotationBean {
  @Qualifier("innerBean1")
  @Bean()
  public InnerBean innerBean1() {
    return new InnerBean();
  }
  @Bean
  public InnerBeanFactory innerBeanFactory() {
    InnerBeanFactory factory = new InnerBeanFactory();
    factory.setInnerBean(innerBean1());
    return factory;
  }
  public static class InnerBean {
  }
  @Data
  public static class InnerBeanFactory {
    private InnerBean innerBean;
  }
}

AnnotationTest.java

@Test
void test7() {
  AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(BASE_PACKAGE);
  Object bean1 = applicationContext.getBean("innerBean1");
  Object factoryBean = applicationContext.getBean("innerBeanFactory");
  int hashCode1 = bean1.hashCode();
  InnerBean innerBeanViaFactory = ((InnerBeanFactory) factoryBean).getInnerBean();
  int hashCode2 = innerBeanViaFactory.hashCode();
  Assertions.assertEquals(hashCode1, hashCode2);
}

大家可以先猜猜看,這個test7()的執(zhí)行結果究竟是成功呢還是失敗呢?

答案是失敗的。如果將AnnotationBean的注解從 @Component 換成 @Configuration,那test7()就會執(zhí)行成功。

究竟是為什么呢?通常 Spring 管理的 bean 不都是單例的么?

別急,讓筆者慢慢道來 ~~~

Spring-source-5.2.8 兩個注解聲明

以下是摘自 Spring-source-5.2.8 的兩個注解的聲明

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Indexed
public @interface Component {
    /**
     * The value may indicate a suggestion for a logical component name,
     * to be turned into a Spring bean in case of an autodetected component.
     * @return the suggested component name, if any (or empty String otherwise)
     */
    String value() default "";
}
---------------------------------- 這是分割線 -----------------------------------
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Configuration {
    /**
     * Explicitly specify the name of the Spring bean definition associated with the
     * {@code @Configuration} class. If left unspecified (the common case), a bean
     * name will be automatically generated.
     * <p>The custom name applies only if the {@code @Configuration} class is picked
     * up via component scanning or supplied directly to an
     * {@link AnnotationConfigApplicationContext}. If the {@code @Configuration} class
     * is registered as a traditional XML bean definition, the name/id of the bean
     * element will take precedence.
     * @return the explicit component name, if any (or empty String otherwise)
     * @see AnnotationBeanNameGenerator
     */
    @AliasFor(annotation = Component.class)
    String value() default "";
    /**
     * Specify whether {@code @Bean} methods should get proxied in order to enforce
     * bean lifecycle behavior, e.g. to return shared singleton bean instances even
     * in case of direct {@code @Bean} method calls in user code. This feature
     * requires method interception, implemented through a runtime-generated CGLIB
     * subclass which comes with limitations such as the configuration class and
     * its methods not being allowed to declare {@code final}.
     * <p>The default is {@code true}, allowing for 'inter-bean references' via direct
     * method calls within the configuration class as well as for external calls to
     * this configuration's {@code @Bean} methods, e.g. from another configuration class.
     * If this is not needed since each of this particular configuration's {@code @Bean}
     * methods is self-contained and designed as a plain factory method for container use,
     * switch this flag to {@code false} in order to avoid CGLIB subclass processing.
     * <p>Turning off bean method interception effectively processes {@code @Bean}
     * methods individually like when declared on non-{@code @Configuration} classes,
     * a.k.a. "@Bean Lite Mode" (see {@link Bean @Bean's javadoc}). It is therefore
     * behaviorally equivalent to removing the {@code @Configuration} stereotype.
     * @since 5.2
     */
    boolean proxyBeanMethods() default true;
}

從這兩個注解的定義中,可能大家已經看出了一點端倪:@Configuration 比 @Component 多一個成員變量 boolean proxyBeanMethods() 默認值是 true. 從這個成員變量的注釋中,我們可以看到一句話 

Specify whether {@code @Bean} methods should get proxied in order to enforce bean lifecycle behavior, e.g. to return shared singleton bean instances even in case of direct {@code @Bean} method calls in user code. 

其實從這句話,我們就可以初步得到我們想要的答案了:在帶有 @Configuration 注解的類中,一個帶有 @Bean 注解的方法顯式調用另一個帶有 @Bean 注解的方法,返回的是共享的單例對象. 下面我們從 Spring 源碼實現角度來看看這中間的原理.

從 Spring 源碼實現中可以得出一個規(guī)律,Spring 作者在實現注解時,通常是先收集解析,再調用。@Configuration是 基于 @Component 實現的,在 @Component 的解析過程中,我們可以看到下面一段邏輯:

org.springframework.context.annotation.ConfigurationClassUtils#checkConfigurationClassCandidate

Map<String, Object> config = metadata.getAnnotationAttributes(Configuration.class.getName());
if (config != null && !Boolean.FALSE.equals(config.get("proxyBeanMethods"))) {
  beanDef.setAttribute(CONFIGURATION_CLASS_ATTRIBUTE, CONFIGURATION_CLASS_FULL);
}
else if (config != null || isConfigurationCandidate(metadata)) {
  beanDef.setAttribute(CONFIGURATION_CLASS_ATTRIBUTE, CONFIGURATION_CLASS_LITE);
}

默認情況下,Spring 在將帶有 @Configuration 注解的類封裝成 BeanDefinition 的時候,會設置一個屬性 CONFIGURATION_CLASS_ATTRIBUTE,屬性值為 CONFIGURATION_CLASS_FULL, 反之,如果只有 @Component 注解,那該屬性值就會是 CONFIGURATION_CLASS_LITE (這個屬性值很重要). 在 @Component 注解的調用過程當中,有下面一段邏輯:

org.springframework.context.annotation.ConfigurationClassPostProcessor#enhanceConfigurationClasses

for (String beanName : beanFactory.getBeanDefinitionNames()) {
  ......
  if ((configClassAttr != null || methodMetadata != null) && beanDef instanceof AbstractBeanDefinition) {
    ......
    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();
......

如果 BeanDefinition 的 ConfigurationClassUtils.CONFIGURATION_CLASS_ATTRIBUTE 屬性值為 ConfigurationClassUtils.CONFIGURATION_CLASS_FULL, 則該 BeanDefinition 對象會被加入到 Map<String, AbstractBeanDefinition> configBeanDefs 容器中。

如果 Spring 發(fā)現該 Map 是空的,則認為不需要進行代理增強,立即返回;反之,則為該類 (本文中,被代理類即為 AnnotationBean, 以下簡稱該類) 創(chuàng)建代理。

所以如果該類的注解是 @Component,調用帶有 @Bean 注解的 innerBean1() 方法時,this 對象為 Spring 容器中的真實單例對象,例如 AnnotationBean@4149.

@Bean
public InnerBeanFactory innerBeanFactory() {
  InnerBeanFactory factory = new InnerBeanFactory();
  factory.setInnerBean(innerBean1());
  return factory;
}

那在上述方法中每調用一次 innerBean1() 方法時,勢必會返回一個新創(chuàng)建的 InnerBean 對象。如果該類的注解為 @Configuration 時,this 對象為 Spring 生成的 AnnotationBean 的代理對象,例如 AnnotationBean$$EnhancerBySpringCGLIB$$90f8540c@4296,

增強邏輯

// The callbacks to use. Note that these callbacks must be stateless.
private static final Callback[] CALLBACKS = new Callback[] {
  new BeanMethodInterceptor(),
  new BeanFactoryAwareMethodInterceptor(),
  NoOp.INSTANCE
};
----------------------------------- 這是分割線 -------------------------------
/**
  * Creates a new CGLIB {@link Enhancer} instance.
  */
  private Enhancer newEnhancer(Class<?> configSuperClass, @Nullable ClassLoader classLoader) {
    Enhancer enhancer = new Enhancer();
    enhancer.setSuperclass(configSuperClass);
    enhancer.setInterfaces(new Class<?>[] {EnhancedConfiguration.class});
    enhancer.setUseFactory(false);
    enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE);
    enhancer.setStrategy(new BeanFactoryAwareGeneratorStrategy(classLoader));
    enhancer.setCallbackFilter(CALLBACK_FILTER);
    enhancer.setCallbackTypes(CALLBACK_FILTER.getCallbackTypes());
    return enhancer;
}

當在上述方法中調用 innerBean1() 時,ConfigurationClassEnhancer 遍歷 3 種回調方法判斷當前調用應該使用哪個回調方法時,第一個回調類型匹配成功org.springframework.context.annotation.ConfigurationClassEnhancer.BeanMethodInterceptor#isMatch 匹配過程如下所示:

@Override
public boolean isMatch(Method candidateMethod) {
  return (candidateMethod.getDeclaringClass() != Object.class && !BeanFactoryAwareMethodInterceptor.isSetBeanFactory(candidateMethod) && BeanAnnotationHelper.isBeanAnnotated(candidateMethod));
}

匹配成功之后,使用 org.springframework.context.annotation.ConfigurationClassEnhancer.BeanMethodInterceptor#intercept 對 innerBean1() 方法調用進行攔截. 在本例中,innerBean1() 被增強器調用了兩次,第一次調用是 Spring 解析帶有 @Bean 注解的 innerBean1() 方法,將構造的 InnerBean 對象加入 Spring 單例池中. 第二次調用是 Spring 解析帶有 @Bean 注解的 innerBeanFactory() 方法,在該方法中顯式調用 innerBean1(). 在第二次調用時,增強過程如下所示:
org.springframework.context.annotation.ConfigurationClassEnhancer.BeanMethodInterceptor#resolveBeanReference

Object beanInstance = (useArgs ? beanFactory.getBean(beanName, beanMethodArgs) : beanFactory.getBean(beanName));

看到這里,相信大家和筆者一樣,對 @Component 和 @Configuration 注解的區(qū)別豁然開朗:
默認情況下,帶有 @Configuration 的類在被 Spring 解析時,會使用切面進行字節(jié)碼增強,在解析帶有 @Bean的方法 innerBeanFactory() 時,該方法內部顯式調用了另一個帶有 @Bean 注解的方法 innerBean1(), 那么返回的對象和 Spring 第一次解析帶有 @Bean 注解的方法 innerBean1() 生成的單例對象是同一個.

以上就是Component和Configuration注解區(qū)別實例詳解的詳細內容,更多關于Component Configuration區(qū)別的資料請關注腳本之家其它相關文章!

相關文章

  • Java中包裝類介紹與其注意事項

    Java中包裝類介紹與其注意事項

    Java語言是一個面向對象的語言,但是Java中的基本數據類型卻是不面向對象的,這在實際使用時存在很多的不便,所以在設計類時為每個基本數據類型設計了一個對應的類進行代表,這樣八個和基本數據類型對應的類統稱為包裝類,有些地方也翻譯為外覆類或數據類型類。
    2017-02-02
  • Java深入分析動態(tài)代理

    Java深入分析動態(tài)代理

    動態(tài)代理指的是,代理類和目標類的關系在程序運行的時候確定的,客戶通過代理類來調用目標對象的方法,是在程序運行時根據需要動態(tài)的創(chuàng)建目標類的代理對象。本文將通過案例詳細講解一下Java動態(tài)代理的原理及實現,需要的可以參考一下
    2022-07-07
  • java命令執(zhí)行jar包的多種方法(四種方法)

    java命令執(zhí)行jar包的多種方法(四種方法)

    本文通過四種方法給大家介紹java命令執(zhí)行jar包的方式,每種方法通過實例代碼給大家詳解,需要的朋友參考下吧
    2019-11-11
  • idea中怎樣創(chuàng)建并運行第一個java程序

    idea中怎樣創(chuàng)建并運行第一個java程序

    這篇文章主要介紹了idea中怎樣創(chuàng)建并運行第一個java程序問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-08-08
  • java控制臺輸入示例分享

    java控制臺輸入示例分享

    這篇文章主要介紹了java控制臺輸入示例分享,需要的朋友可以參考下
    2014-03-03
  • java事務回滾失敗問題分析

    java事務回滾失敗問題分析

    這篇文章主要介紹了java事務回滾失敗問題分析,具有一定借鑒價值,需要的朋友可以參考下
    2018-01-01
  • 詳解Java中的reactive stream協議

    詳解Java中的reactive stream協議

    Stream大家應該都很熟悉了,java8中為所有的集合類都引入了Stream的概念。優(yōu)雅的鏈式操作,流式處理邏輯,相信用過的人都會愛不釋手。本文將詳細介紹Java中的reactive stream協議。
    2021-06-06
  • Java如何通過jstack命令查詢日志

    Java如何通過jstack命令查詢日志

    在分析線上問題時常使用到jstack?<PID>命令將當時Java應用程序的線程堆棧dump出來,面對jstack?日志,我們如何查看?下面小編給大家介紹下Java如何通過jstack命令查詢日志,感興趣的朋友一起看看吧
    2023-03-03
  • Java包裝類的概述與應用

    Java包裝類的概述與應用

    包裝類使用起來非常方便,但是沒有對應的方法來操作這些基本數據類型,可以使用一個類,把基本類型的數據裝起來,在類中定義一些方法,我們可以使用類中的方法來操作這些基本類型的數據,這篇文章主要給大家介紹了關于Java包裝類的相關資料,需要的朋友可以參考下
    2022-04-04
  • Java中利用Alibaba開源技術EasyExcel來操作Excel表的示例代碼

    Java中利用Alibaba開源技術EasyExcel來操作Excel表的示例代碼

    這篇文章主要介紹了Java中利用Alibaba開源技術EasyExcel來操作Excel表的示例代碼,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2021-03-03

最新評論

团风县| 台湾省| 磴口县| 奉新县| 新竹市| 永寿县| 大名县| 吴桥县| 舞钢市| 孙吴县| 兴安盟| 志丹县| 乡城县| 洛隆县| 惠水县| 衡阳县| 邹城市| 远安县| 泰安市| 芷江| 阿瓦提县| 沙田区| 海口市| 梅河口市| 长治县| 旬邑县| 乐清市| 澎湖县| 双流县| 库尔勒市| 青州市| 湘西| 新巴尔虎左旗| 卢龙县| 安宁市| 灵寿县| 衡东县| 离岛区| 津南区| 广昌县| 石棉县|