小白面试题:@Component和@Bean的区别

Posted 长安紫薯

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了小白面试题:@Component和@Bean的区别相关的知识,希望对你有一定的参考价值。

这两个注解的相同点是,他们都能完成创建实例,加入容器。但它们实现的方式差异很大。

@Component (@Controller @Service @Respository)作用于类class上,只有在我们的SpringBoot应用程序启用了组件扫描并且包含了被注解的类时才有效。通过组件扫描,Spring将扫描整个类路径,并将所有@Component注释类添加到Spring容器。

@Bean相对来说就更加灵活了,它可以独立加在方法method上,按需注册到spring容器。
而且如果你要用到第三方类库里面某个方法的时候,你就只能用@Bean把这个方法注册到spring容器,因为用@Component注解是要写在类中的。

=@Bean 的用法=
@Bean是一个方法级别上的注解,主要用在@Configuration注解的类里,也可以用在@Component注解的类里。添加的bean的id为方法名

定义bean
下面是@Configuration里的一个事务的例子

@Configuration
public class AppConfig {

    @Bean
    public TransferService transferService() {
        return new TransferServiceImpl();
    }

}

这个配置就等同于之前在xml里的配置

<beans>
    <bean id="transferService" class="cn.tedu.TransferServiceImpl"/>
</beans>

bean的依赖
@bean 也可以依赖其他任意数量的bean,如果TransferService 依赖 AccountRepository,我们可以通过方法参数实现这个依赖

@Configuration
public class AppConfig {

    @Bean
    public TransferService transferService(ProductRepository productRepository) {
        return new TransferServiceImpl(productRepository);
    }

}

以上是关于小白面试题:@Component和@Bean的区别的主要内容,如果未能解决你的问题,请参考以下文章

小白面试题:@Component@Controller@Service@Respository的区别

面试必问|Spring @bean 和 @component 注解有什么区别?

Java面试题:Spring中如何使用注解来配置Bean?有哪些相关的注解?

小白面试题:Spring中Bean的初始化过程

面试官:@Configuration 和 @Component 注解的区别?大部分人都会答错!

面试官:@Configuration 和 @Component 注解的区别?大部分人都会答错!