What is the difference between @Configuration and @Component in Spring?

后端 未结 5 1127
感动是毒
感动是毒 2020-12-05 00:00

@ComponentScan creates beans using both @Configuration and @Component. Both these annotations work fine when swapped. What is the diff

5条回答
  •  -上瘾入骨i
    2020-12-05 00:30

    Actually answer is not complete, is it true that:

    @Component Indicates that an annotated class is a "component". Such classes are considered as candidates for auto-detection when using annotation-based configuration and classpath scanning.

    But you do can create i.e MyConfiguration.java class then stereotype with @Component and add @Beans declaration to it. In this way it will looks as a configuration, main difference is that when annotated class with @Configuration @Bean annotated methods are proxy using CGLIB which made in code calls after the first one to return bean from context instead of execute method again and create another instance as happens when using @Component with @Bean

提交回复
热议问题