@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;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
@Bean 需要在配置类中使用,即类上需要加上@Configuration注解


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

}
1
2
3
4
5
6
7
8
9
10
两者都可以通过@Autowired装配

@Autowired
Student student;
1
2
那为什么有了@Compent,还需要@Bean呢?
如果你想要将第三方库中的组件装配到你的应用中,在这种情况下,是没有办法在它的类上添加@Component注解的,因此就不能使用自动化装配的方案了,但是我们可以使用@Bean,当然也可以使用XML配置。
————————————————
版权声明:本文为CSDN博主「荼渔」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_38534144/article/details/82414201

 

 

最近翻了一下Spring In Action,看完前三章发现@Bean和@Component用得挺多,不过对这两者的区别不是很清楚,书中也没有详细介绍。

Google了一下,发现一篇文章写得不错,不过是纯英文的:http://www.tomaszezula.com/2014/02/09/spring-series-part-5-component-vs-bean/

下面是看过上面文章之后自己的一些理解:

首先我们看看这两个注解的作用:

  • @Component注解表明一个类会作为组件类,并告知Spring要为这个类创建bean。

  • @Bean注解告诉Spring这个方法将会返回一个对象,这个对象要注册为Spring应用上下文中的bean。通常方法体中包含了最终产生bean实例的逻辑。

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

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

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

举个栗子:

@Controller

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

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

而@Bean的用途则更加灵活

当我们引用第三方库中的类需要装配到Spring容器时,则只能通过@Bean来实现

举个例子:

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实现不了的自定义加载类。



作者:jasperchen
链接:https://www.jianshu.com/p/3fbfbb843b63
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

posted on 2022-06-20 18:00  ExplorerMan  阅读(211)  评论(0编辑  收藏  举报

导航