Spring中@Component与@Bean的区别

个人博客地址:https://griabcrh.github.io/

Spring帮助我们管理bean分为两个部分,一个是注册Bean,一个是装配Bean。
完成这两个动作有三种方式,一种是使用自动配置的方式,一种是使用JavaConfig的方式,一种就是使用XML配置的方式。

首先我们来看看两个注解的作用:
  • @Component注解表明一个类会作为组件类,并告知Spring要为这个类创建bean。

  • @Bean注解告诉Spring这个方法将会返回一个对象,这个对象要注册为Spring应用上下文中的bean。

两者的目的是一样的,都是注册bean到Spring容器中。

@Component(@Controller、@Service、@Repository)通常是通过类路径扫描来自动侦测以及自动装配到Spring容器中。

而@Bean注解通常是我们在标有该注解的方法中定义产生这个bean的逻辑。

举个例子:

@Controller

//在这里用Component,Controller,Service,Repository都可以起到相同的作用。

@RequestMapping(″/web/controller1″)
public class WebController {
    .....
}

@Component
public class Student {
 
    private String name = "lkm";
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
}

@Bean 需要在配置类中使用,即类上需要加上@Configuration注解

@Configuration
public class WebSocketConfig {
    @Bean
    public Student student(){
        return new Student();
    }
 
}

两者都可以通过@Autowired装配

@Autowired
Student student;
那为什么有了@Compent,还需要@Bean呢?

如果你想要将第三方库中的组件装配到你的应用中,在这种情况下,是没有办法在它的类上添加@Component注解的,因此就不能使用自动化装配的方案了,但是我们可以使用@Bean,当然也可以使用XML配置。

举个例子:

public class WireThirdLibClass {
    @Bean
    public ThirdLibClass getThirdLibClass() {
        return new ThirdLibClass();
    }
}

再举个只能用@Bean的例子:

@Bean
public OneService getService(status) {
    case (status)  {
        when 1:
                return new serviceImpl1();
        when 2:
                return new serviceImpl2();
        when 3:
                return new serviceImpl3();
    }
}

以上这个例子是无法用Component以及其具体实现注解(Controller、Service、Repository)来实现的。

总结:

@Component和@Bean都是用来注册Bean并装配到Spring容器中,但是Bean比Component的自定义性更强。可以实现一些Component实现不了的自定义加载类。

如果你喜欢本文,请长按二维码关注
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Java开发高级进阶公众号

苦不堪言

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值