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í)行結(jié)果究竟是成功呢還是失敗呢?
答案是失敗的。如果將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;
}從這兩個注解的定義中,可能大家已經(jīng)看出了一點端倪:@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 注解的方法顯式調(diào)用另一個帶有 @Bean 注解的方法,返回的是共享的單例對象. 下面我們從 Spring 源碼實現(xiàn)角度來看看這中間的原理.
從 Spring 源碼實現(xiàn)中可以得出一個規(guī)律,Spring 作者在實現(xiàn)注解時,通常是先收集解析,再調(diào)用。@Configuration是 基于 @Component 實現(xiàn)的,在 @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 的時候,會設(shè)置一個屬性 CONFIGURATION_CLASS_ATTRIBUTE,屬性值為 CONFIGURATION_CLASS_FULL, 反之,如果只有 @Component 注解,那該屬性值就會是 CONFIGURATION_CLASS_LITE (這個屬性值很重要). 在 @Component 注解的調(diào)用過程當中,有下面一段邏輯:
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ā)現(xiàn)該 Map 是空的,則認為不需要進行代理增強,立即返回;反之,則為該類 (本文中,被代理類即為 AnnotationBean, 以下簡稱該類) 創(chuàng)建代理。
所以如果該類的注解是 @Component,調(diào)用帶有 @Bean 注解的 innerBean1() 方法時,this 對象為 Spring 容器中的真實單例對象,例如 AnnotationBean@4149.
@Bean
public InnerBeanFactory innerBeanFactory() {
InnerBeanFactory factory = new InnerBeanFactory();
factory.setInnerBean(innerBean1());
return factory;
}那在上述方法中每調(diào)用一次 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;
}當在上述方法中調(diào)用 innerBean1() 時,ConfigurationClassEnhancer 遍歷 3 種回調(diào)方法判斷當前調(diào)用應(yīng)該使用哪個回調(diào)方法時,第一個回調(diào)類型匹配成功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() 方法調(diào)用進行攔截. 在本例中,innerBean1() 被增強器調(diào)用了兩次,第一次調(diào)用是 Spring 解析帶有 @Bean 注解的 innerBean1() 方法,將構(gòu)造的 InnerBean 對象加入 Spring 單例池中. 第二次調(diào)用是 Spring 解析帶有 @Bean 注解的 innerBeanFactory() 方法,在該方法中顯式調(diào)用 innerBean1(). 在第二次調(diào)用時,增強過程如下所示: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() 時,該方法內(nèi)部顯式調(diào)用了另一個帶有 @Bean 注解的方法 innerBean1(), 那么返回的對象和 Spring 第一次解析帶有 @Bean 注解的方法 innerBean1() 生成的單例對象是同一個.
以上就是Component和Configuration注解區(qū)別實例詳解的詳細內(nèi)容,更多關(guān)于Component Configuration區(qū)別的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
springboot 多數(shù)據(jù)源配置不生效遇到的坑及解決
這篇文章主要介紹了springboot 多數(shù)據(jù)源配置不生效遇到的坑及解決,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-11-11
解決spring懶加載以及@PostConstruct結(jié)合的坑
這篇文章主要介紹了解決spring懶加載以及@PostConstruct結(jié)合的坑,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-12-12
Kafka多節(jié)點分布式集群搭建實現(xiàn)過程詳解
這篇文章主要介紹了Kafka多節(jié)點分布式集群搭建實現(xiàn)過程詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-11-11
Mybatis?Plus?QueryWrapper復合用法詳解
這篇文章主要介紹了Mybatis?Plus?QueryWrapper復合用法詳解,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教。2022-01-01
xxl-job定時任務(wù)配置應(yīng)用及添加到springboot項目中實現(xiàn)動態(tài)API調(diào)用
XXL-JOB是一個分布式任務(wù)調(diào)度平臺,其核心設(shè)計目標是開發(fā)迅速、學習簡單、輕量級、易擴展,本篇文章主要是對xuxueli的xxl-job做一個簡單的配置,以及將其添加到自己已有的項目中進行api調(diào)用,感興趣的朋友跟隨小編一起看看吧2024-04-04
SpringBoot請求處理之常用參數(shù)注解介紹與源碼分析
SpringBoot是一種整合Spring技術(shù)棧的方式(或者說是框架),同時也是簡化Spring的一種快速開發(fā)的腳手架,本篇讓我們一起學習請求處理、常用注解和方法參數(shù)的小技巧2022-10-10
SpringSecurity實現(xiàn)前后端分離的示例詳解
Spring Security默認提供賬號密碼認證方式,具體實現(xiàn)是在UsernamePasswordAuthenticationFilter 中,這篇文章主要介紹了SpringSecurity實現(xiàn)前后端分離的示例詳解,需要的朋友可以參考下2023-03-03

