@Component 和,@Bean和@ImportResource的区别

spring帮助我们管理Bean分为两个部分,一个是注册Bean,一个装配Bean。
完成这两个动作有三种方式:

  • 一种是使用自动配置的方式:@Compent
  • 一种是使用JavaConfig的方式:@Configuration再结合@Bean
  • 一种就是使用XML配置的方式:< bean id=“student” class=“com.apple.Student”/>

在自动配置的方式中,使用@Component去告诉Spring,我是一个bean,你要来管理我,然后使用@AutoWired注解去装配Bean(所谓装配,就是管理对象直接的协作关系)。然后在JavaConfig中,@Configuration其实就是告诉spring,spring容器要怎么配置(怎么去注册bean,怎么去处理bean之间的关系(装配))。那么久很好理解了,@Bean的意思就是,我要获取这个bean的时候,你spring要按照这种方式去帮我获取到这个bean。到了使用xml的方式,也是如此。君不见< bean >标签就是告诉spring怎么获取这个bean,各种就是手动的配置bean之间的关系。

@Compent 作用其实就是自动装配,也相当于 XML配置,

@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;

PS: springboot中的@SpringBootApplication:申明让spring boot自动给程序进行必要的配置,这个配置等同于:
@Configuration ,@EnableAutoConfiguration 和 @ComponentScan 三个配置。所以也可以直接在启动类里面加上第三方要注入的Bean
总结:
那为什么有了@Compent,还需要@Bean呢?
如果你想要将第三方库中的组件装配到你的应用中,在这种情况下,是没有办法在它的类上添加@Component注解的,因此就不能使用自动化装配的方案了,但是我们可以使用@Bean,当然也可以使用XML配置。
还有一种情况是,在common模块中写了类,在别的模块中需要导入使用,也可以使用@Bean的方式,比如:IdWorker生成类。
然后:

@Autowired    
private IdWorker idWorker; 

@ImportResource
@ImportResource要配和@Configuration或者是@SpringBootApplication使用,,用于将applicationContext.xml文件中的bean加载到Application Context中。

@Configuration
@ImportResource({"classpath*:applicationContext.xml"})
public class XmlConfiguration {
}

@ImportResource等同于xml配置:
<import resource="cons-injec.xml" />

@Import注解是引入带有@Configuration的java类。
@ImportResource是引入spring配置文件.xml

其他:
springboot注解与xml配置对应关系

context:component-scan                                 @ComponentScan
<context:component-scan base-package="com.apple"/>               @ComponentScan("com.apple")

参考文章:
https://segmentfault.com/a/1190000014119872?utm_source=tag-newest
https://blog.csdn.net/qq_38534144/article/details/82414201
https://blog.csdn.net/tuoni123/article/details/79985359

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Apple_Web

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值