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

相同点:

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

  • 10
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值