SpringBoot中 @Bean 和 @Component的联系区别

您所在的位置:网站首页 component注解的作用 SpringBoot中 @Bean 和 @Component的联系区别

SpringBoot中 @Bean 和 @Component的联系区别

2023-08-21 18:24| 来源: 网络整理| 查看: 265

相同点: @Component 和 @Bean 是两种使用注解来定义bean的方式。@Component和@Bean的目的是一样的,都是注册bean到Spring容器中。两者都可以通过@Autowired装配 不同点:

@Component 和 它的子类型(@Controller, @Service and @Repository)注释在类上。告诉Spring,我是一个bean,通过类路径扫描自动检测并注入到Spring容器中。

@Bean不能注释在类上,只能用于在配置类(@Configuration)中显式声明单个bean。意思就是,我要获取这个bean的时候,spring要按照这种方式去获取这个bean。默认情况下@Bean注释的方法名作为对象的名字,也可以用name属性定义对象的名字。

两者的使用场景

装配第三方库中的组件时,在这种情况下,是没有办法在它的类上添加@Component注解的,这时候使用配置类@Configuration和@Bean搭配的方式,实现自动化装配。

代码验证 @Component使用 @Controller @RequestMapping("/web") public class WebController { @ResponseBody @RequestMapping("/msg") public String message(){ return "msg"; } } @Component @RequestMapping("/web") public class WebController { @ResponseBody @RequestMapping("/msg") public String message(){ return "msg"; } } @Service @RequestMapping("/web") public class WebController { @ResponseBody @RequestMapping("/msg") public String message(){ return "msg"; } }

访问url=locahost:8080/web/msg,三段代码均返回字符串msg。表明注解标注的类被容器接管(此web项目我自己用的端口8080)

@Bean使用 // Just a POJO public class MessageBuilder { public String getMsg(){ return "msgBuilder"; } } import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; // Let's turn the POJO into a bean @Configuration public class AppConfig { @Bean public MessageBuilder messageBuilder(){ return new MessageBuilder(); } } @Controller @RequestMapping("/web") public class WebController { // Finally, hook it up @Autowired private MessageBuilder messageBuilder; @ResponseBody @RequestMapping("/msg") public String message(){ return messageBuilder.getMsg(); } }

https://www.cnblogs.com/zoe-java/p/11542484.html https://blog.csdn.net/w605283073/article/details/89221522



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3