@Component @Configuration

来源:4-4 统一配置的开发

abel_星123

2019-02-20

老师,这个两个注解不是都相当于把一个类类作为spring的xml配置文件中的 吗?主要的区别是什么?

写回答

1回答

张勤一

2019-02-20

同学你好:

    @Configuration 注解本质上还是 @Component,所以,是可以替换的。且配置类用 @Configuration 标注在语义上也会更加标准。

    可以参考 @Configuration 的源码:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Configuration {

   /**
    * Explicitly specify the name of the Spring bean definition associated
    * with this Configuration class. If left unspecified (the common case),
    * a bean name will be automatically generated.
    * <p>The custom name applies only if the Configuration class is picked up via
    * component scanning or supplied directly to a {@link AnnotationConfigApplicationContext}.
    * If the Configuration class is registered as a traditional XML bean definition,
    * the name/id of the bean element will take precedence.
    * @return the suggested component name, if any (or empty String otherwise)
    * @see org.springframework.beans.factory.support.DefaultBeanNameGenerator
    */
   String value() default "";

}

    可以看到,Configuration 实际是标注了 @Component 的。


    欢迎来 QQ 群随时交流、讨论,也非常感谢同学的支持! 


3
0

Spring Cloud微服务架构 设计实现广告系统

广告营销系统,未来大中型企业的标配

2136 学习 · 927 问题

查看课程