zoukankan      html  css  js  c++  java
  • [转载]@Component 和 @Bean 的区别

    @Component 和 @Bean 的区别

    @Component 和 @Bean 的区别

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

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

    那为什么有了@Compent,还需要@Bean呢?

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

  • 相关阅读:
    单调栈模板
    Yet Another Broken Keyboard[双指针]
    经典递归集合
    [未完成]ECRound 80
    #614 C. NEKO's Maze Game[简易DFS,0|1转换]
    等差数列异或和模板
    线段树基础题
    前缀和&差分
    优先队列
    st表模板
  • 原文地址:https://www.cnblogs.com/JuncaiF/p/11153318.html
Copyright © 2011-2022 走看看