欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Spring注解@Configuration和@Component區(qū)別詳解

 更新時(shí)間:2023年04月07日 11:11:23   作者:isea533  
@Component和@Configuration都可以作為配置類,之前一直都沒(méi)覺(jué)得這兩個(gè)用起來(lái)有什么差別,可能有時(shí)程序跑的和自己想的有所區(qū)別也沒(méi)注意到,下面這篇文章主要給大家介紹了關(guān)于Spring注解@Configuration和@Component區(qū)別的相關(guān)資料,需要的朋友可以參考下

Spring @Configuration 和 @Component 區(qū)別

一句話概括就是 @Configuration 中所有帶 @Bean 注解的方法都會(huì)被動(dòng)態(tài)代理,因此調(diào)用該方法返回的都是同一個(gè)實(shí)例。

下面看看實(shí)現(xiàn)的細(xì)節(jié)。

@Configuration 注解:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Configuration {
    String value() default "";
}

從定義來(lái)看, @Configuration 注解本質(zhì)上還是 @Component,因此 <context:component-scan/> 或者 @ComponentScan 都能處理@Configuration 注解的類。

@Configuration 標(biāo)記的類必須符合下面的要求:

  • 配置類必須以類的形式提供(不能是工廠方法返回的實(shí)例),允許通過(guò)生成子類在運(yùn)行時(shí)增強(qiáng)(cglib 動(dòng)態(tài)代理)。
  • 配置類不能是 final 類(沒(méi)法動(dòng)態(tài)代理)。
  • 配置注解通常為了通過(guò) @Bean 注解生成 Spring 容器管理的類,
  • 配置類必須是非本地的(即不能在方法中聲明,不能是 private)。
  • 任何嵌套配置類都必須聲明為static。
  • @Bean 方法可能不會(huì)反過(guò)來(lái)創(chuàng)建進(jìn)一步的配置類(也就是返回的 bean 如果帶有 @Configuration,也不會(huì)被特殊處理,只會(huì)作為普通的 bean)。

加載過(guò)程

Spring 容器在啟動(dòng)時(shí),會(huì)加載默認(rèn)的一些 PostPRocessor,其中就有 ConfigurationClassPostProcessor,這個(gè)后置處理程序?qū)iT處理帶有 @Configuration 注解的類,這個(gè)程序會(huì)在 bean 定義加載完成后,在 bean 初始化前進(jìn)行處理。主要處理的過(guò)程就是使用 cglib 動(dòng)態(tài)代理增強(qiáng)類,而且是對(duì)其中帶有 @Bean 注解的方法進(jìn)行處理。

ConfigurationClassPostProcessor 中的 postProcessBeanFactory 方法中調(diào)用了下面的方法:

/**
 * Post-processes a BeanFactory in search of Configuration class BeanDefinitions;
 * any candidates are then enhanced by a {@link ConfigurationClassEnhancer}.
 * Candidate status is determined by BeanDefinition attribute metadata.
 * @see ConfigurationClassEnhancer
 */
public void enhanceConfigurationClasses(ConfigurableListableBeanFactory beanFactory) {
    Map<String, AbstractBeanDefinition> configBeanDefs = new LinkedHashMap<String, AbstractBeanDefinition>();
    for (String beanName : beanFactory.getBeanDefinitionNames()) {
        BeanDefinition beanDef = beanFactory.getBeanDefinition(beanName);
        if (ConfigurationClassUtils.isFullConfigurationClass(beanDef)) {
            //省略部分代碼
            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);
        try {
            // Set enhanced subclass of the user-specified bean class
            Class<?> configClass = beanDef.resolveBeanClass(this.beanClassLoader);
            Class<?> enhancedClass = enhancer.enhance(configClass, this.beanClassLoader);
            if (configClass != enhancedClass) {
                //省略部分代碼
                beanDef.setBeanClass(enhancedClass);
            }
        }
        catch (Throwable ex) {
            throw new IllegalStateException(
              "Cannot load configuration class: " + beanDef.getBeanClassName(), ex);
        }
    }
}

在方法的第一次循環(huán)中,查找到所有帶有 @Configuration 注解的 bean 定義,然后在第二個(gè) for 循環(huán)中,通過(guò)下面的方法對(duì)類進(jìn)行增強(qiáng):

Class<?> enhancedClass = enhancer.enhance(configClass, this.beanClassLoader);

然后使用增強(qiáng)后的類替換了原有的 beanClass

beanDef.setBeanClass(enhancedClass);

所以到此時(shí),所有帶有 @Configuration 注解的 bean 都已經(jīng)變成了增強(qiáng)的類。

下面關(guān)注上面的 enhance 增強(qiáng)方法,多跟一步就能看到下面的方法:

/**
 * Creates a new CGLIB {@link Enhancer} instance.
 */
private Enhancer newEnhancer(Class<?> superclass, ClassLoader classLoader) {
    Enhancer enhancer = new Enhancer();
    enhancer.setSuperclass(superclass);
    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;
}

通過(guò) cglib 代理的類在調(diào)用方法時(shí),會(huì)通過(guò) CallbackFilter 調(diào)用,這里的 CALLBACK_FILTER 如下:

// The callbacks to use. Note that these callbacks must be stateless.
private static final Callback[] CALLBACKS = new Callback[] {
        new BeanMethodInterceptor(),
        new BeanFactoryAwareMethodInterceptor(),
        NoOp.INSTANCE
};

private static final ConditionalCallbackFilter CALLBACK_FILTER = 
        new ConditionalCallbackFilter(CALLBACKS);

其中 BeanMethodInterceptor 匹配方法如下:

@Override
public boolean isMatch(Method candidateMethod) {
    return BeanAnnotationHelper.isBeanAnnotated(candidateMethod);
}

//BeanAnnotationHelper
public static boolean isBeanAnnotated(Method method) {
    return AnnotatedElementUtils.hasAnnotation(method, Bean.class);
}

也就是當(dāng)方法有 @Bean 注解的時(shí)候,就會(huì)執(zhí)行這個(gè)回調(diào)方法。

另一個(gè) BeanFactoryAwareMethodInterceptor 匹配的方法如下:

@Override
public boolean isMatch(Method candidateMethod) {
    return (candidateMethod.getName().equals("setBeanFactory") &&
            candidateMethod.getParameterTypes().length == 1 &&
            BeanFactory.class == candidateMethod.getParameterTypes()[0] &&
            BeanFactoryAware.class.isAssignableFrom(candidateMethod.getDeclaringClass()));
}

當(dāng)前類還需要實(shí)現(xiàn) BeanFactoryAware 接口,上面的 isMatch 就是匹配的這個(gè)接口的方法。

@Bean 注解方法執(zhí)行策略

先給一個(gè)簡(jiǎn)單的示例代碼:

@Configuration
public class MyBeanConfig {

    @Bean
    public Country country(){
        return new Country();
    }

    @Bean
    public UserInfo userInfo(){
        return new UserInfo(country());
    }

}

相信大多數(shù)人第一次看到上面 userInfo() 中調(diào)用 country() 時(shí),會(huì)認(rèn)為這里的 Country 和上面 @Bean 方法返回的 Country 可能不是同一個(gè)對(duì)象,因此可能會(huì)通過(guò)下面的方式來(lái)替代這種方式:

@Autowired
private Country country;

實(shí)際上不需要這么做(后面會(huì)給出需要這樣做的場(chǎng)景),直接調(diào)用 country() 方法返回的是同一個(gè)實(shí)例。

下面看調(diào)用 country()userInfo() 方法時(shí)的邏輯。

現(xiàn)在我們已經(jīng)知道 @Configuration 注解的類是如何被處理的了,現(xiàn)在關(guān)注上面的 BeanMethodInterceptor,看看帶有 @Bean 注解的方法執(zhí)行的邏輯。下面分解來(lái)看 intercept 方法。

//首先通過(guò)反射從增強(qiáng)的 Configuration 注解類中獲取 beanFactory
ConfigurableBeanFactory beanFactory = getBeanFactory(enhancedConfigInstance);

//然后通過(guò)方法獲取 beanName,默認(rèn)為方法名,可以通過(guò) @Bean 注解指定
String beanName = BeanAnnotationHelper.determineBeanNameFor(beanMethod);

//確定這個(gè) bean 是否指定了代理的范圍
//默認(rèn)下面 if 條件 false 不會(huì)執(zhí)行
Scope scope = AnnotatedElementUtils.findMergedAnnotation(beanMethod, Scope.class);
if (scope != null && scope.proxyMode() != ScopedProxyMode.NO) {
    String scopedBeanName = ScopedProxyCreator.getTargetBeanName(beanName);
    if (beanFactory.isCurrentlyInCreation(scopedBeanName)) {
        beanName = scopedBeanName;    }
}

//中間跳過(guò)一段 Factorybean 相關(guān)代碼

//判斷當(dāng)前執(zhí)行的方法是否為正在執(zhí)行的 @Bean 方法
//因?yàn)榇嬖谠?userInfo() 方法中調(diào)用 country() 方法
//如果 country() 也有 @Bean 注解,那么這個(gè)返回值就是 false.
if (isCurrentlyInvokedFactoryMethod(beanMethod)) {
    // 判斷返回值類型,如果是 BeanFactoryPostProcessor 就寫警告日志
    if (logger.isWarnEnabled() &&
            BeanFactoryPostProcessor.class.isAssignableFrom(beanMethod.getReturnType())) {
        logger.warn(String.format(
            "@Bean method %s.%s is non-static and returns an object " +
            "assignable to Spring's BeanFactoryPostProcessor interface. This will " +
            "result in a failure to process annotations such as @Autowired, " +
            "@Resource and @PostConstruct within the method's declaring " +
            "@Configuration class. Add the 'static' modifier to this method to avoid " +
            "these container lifecycle issues; see @Bean javadoc for complete details.",
            beanMethod.getDeclaringClass().getSimpleName(), beanMethod.getName()));
    }
    //直接調(diào)用原方法創(chuàng)建 bean
    return cglibMethodProxy.invokeSuper(enhancedConfigInstance, beanMethodArgs);
}
//如果不滿足上面 if,也就是在 userInfo() 中調(diào)用的 country() 方法
return obtainBeanInstanceFromFactory(beanMethod, beanMethodArgs, beanFactory, beanName);

關(guān)于 isCurrentlyInvokedFactoryMethod 方法

可以參考 SimpleInstantiationStrategy 中的 instantiate 方法,這里先設(shè)置的調(diào)用方法:

currentlyInvokedFactoryMethod.set(factoryMethod);
return factoryMethod.invoke(factoryBean, args);

而通過(guò)方法內(nèi)部直接調(diào)用 country() 方法時(shí),不走上面的邏輯,直接進(jìn)的代理方法,也就是當(dāng)前的 intercept方法,因此當(dāng)前的工廠方法和執(zhí)行的方法就不相同了。

obtainBeanInstanceFromFactory 方法比較簡(jiǎn)單,就是通過(guò) beanFactory.getBean 獲取 Country,如果已經(jīng)創(chuàng)建了就會(huì)直接返回,如果沒(méi)有執(zhí)行過(guò),就會(huì)通過(guò) invokeSuper 首次執(zhí)行。

因此我們?cè)?@Configuration 注解定義的 bean 方法中可以直接調(diào)用方法,不需要 @Autowired 注入后使用。

@Component 注意

@Component 注解并沒(méi)有通過(guò) cglib 來(lái)代理@Bean 方法的調(diào)用,因此像下面這樣配置時(shí),就是兩個(gè)不同的 country。

@Component
public class MyBeanConfig {

    @Bean
    public Country country(){
        return new Country();
    }

    @Bean
    public UserInfo userInfo(){
        return new UserInfo(country());
    }

}

有些特殊情況下,我們不希望 MyBeanConfig 被代理(代理后會(huì)變成WebMvcConfig$$EnhancerBySpringCGLIB$$8bef3235293)時(shí),就得用 @Component,這種情況下,上面的寫法就需要改成下面這樣:

@Component
public class MyBeanConfig {

    @Autowired
    private Country country;

    @Bean
    public Country country(){
        return new Country();
    }

    @Bean
    public UserInfo userInfo(){
        return new UserInfo(country);
    }

}

這種方式可以保證使用的同一個(gè) Country 實(shí)例。

總結(jié)

到此這篇關(guān)于Spring注解@Configuration和@Component區(qū)別的文章就介紹到這了,更多相關(guān)Spring @Configuration和@Component區(qū)別內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • java數(shù)據(jù)庫(kù)連接、查詢、更新等

    java數(shù)據(jù)庫(kù)連接、查詢、更新等

    這篇文章主要介紹了java數(shù)據(jù)庫(kù)連接、查詢、更新等,需要的朋友可以參考下
    2018-05-05
  • 使用spring-cache一行代碼解決緩存擊穿問(wèn)題

    使用spring-cache一行代碼解決緩存擊穿問(wèn)題

    本文主要介紹了使用spring-cache一行代碼解決緩存擊穿問(wèn)題,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2022-04-04
  • SpringMvc導(dǎo)出Excel實(shí)例代碼

    SpringMvc導(dǎo)出Excel實(shí)例代碼

    本篇文章主要介紹了SpringMvc導(dǎo)出Excel實(shí)例代碼,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2017-01-01
  • springboot 啟動(dòng)項(xiàng)目打印接口列表的實(shí)現(xiàn)

    springboot 啟動(dòng)項(xiàng)目打印接口列表的實(shí)現(xiàn)

    這篇文章主要介紹了springboot 啟動(dòng)項(xiàng)目打印接口列表的實(shí)現(xiàn)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-09-09
  • Java之鍵盤輸入語(yǔ)句Scanner解讀

    Java之鍵盤輸入語(yǔ)句Scanner解讀

    這篇文章主要介紹了Java之鍵盤輸入語(yǔ)句Scanner解讀,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-11-11
  • Mapper類中存在名稱相同的方法重載報(bào)錯(cuò)問(wèn)題

    Mapper類中存在名稱相同的方法重載報(bào)錯(cuò)問(wèn)題

    這篇文章主要介紹了Mapper類中存在名稱相同的方法重載報(bào)錯(cuò)問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-03-03
  • Java線程安全的計(jì)數(shù)器簡(jiǎn)單實(shí)現(xiàn)代碼示例

    Java線程安全的計(jì)數(shù)器簡(jiǎn)單實(shí)現(xiàn)代碼示例

    這篇文章主要介紹了Java線程安全的計(jì)數(shù)器簡(jiǎn)單實(shí)現(xiàn)代碼示例,具有一定參考價(jià)值,需要的朋友可以了解下。
    2017-10-10
  • 最新評(píng)論