当前位置: 首页 > news >正文

Spring-boot读书笔记一@Component.vs.@bean

Component vs Bean in Spring Boot

Both are Spring-managed objects, but they differ in how and where they're defined.

@Component
Class-level annotation - marks the class itself as a Spring component

@Component
public class UserService {public void saveUser(String name) {// business logic}
}

Characteristics:

  • Applied directly to the class
  • Spring auto-detects during component scanning
  • One instance per class (unless specified otherwise)
  • Class controls its own creation

@Bean
Method-level annotation - creates beans through factory methods in @Configuration classes

@Configuration
public class AppConfig {@Beanpublic RestTemplate restTemplate() {return new RestTemplate();}@Beanpublic DatabaseService databaseService() {return new DatabaseService("localhost", 5432);}
}

Characteristics:

  • Applied to methods in @Configuration classes
  • You control object creation and configuration
  • Can create multiple beans from same class
  • External configuration of third-party classes

Key Differences
@Component @Bean
Class-level Method-level
Auto-detected Explicitly defined
Own classes Any classes (including third-party)
Simple creation Custom creation logic
One bean per class Multiple beans possible

When to Use Each

  • @Component for:

    1. Your own business classes
    2. Services, repositories, controllers
    3. Simple object creation
  • @Bean for:

    1. Third-party library objects
    2. Complex object configuration
    3. Conditional bean creation
    4. Multiple instances of same class

Both @Component and @Bean result in Spring-managed objects, but @Bean gives more control over the creation process.

http://www.jsqmd.com/news/168074/

相关文章:

  • Miniconda环境下PyTorch模型降级回滚方案
  • SSH密钥认证配置步骤:安全连接运行Miniconda镜像的远程主机
  • GPU算力资源如何高效利用?Miniconda-Python3.10环境调优实战
  • 【2025最新】基于SpringBoot+Vue的线上学习资源智能推荐系统管理系统源码+MyBatis+MySQL
  • Spring-boot读书笔记一Introduction of logging framework of Log4j2
  • Miniconda-Python3.10镜像如何支持多租户GPU算力售卖
  • 使用 K-Means 聚类进行图像分割
  • JLink驱动安装日志分析方法:快速定位错误原因
  • IAR安装教程(STM32):手把手带你完成环境搭建
  • 【2025最新】基于SpringBoot+Vue的乡村养老服务管理系统管理系统源码+MyBatis+MySQL
  • Miniconda-Python3.10镜像如何实现按需付费的Token模式
  • cc2530串口通信项目应用:IAR平台操作指南
  • STM32 USART波特率超详细版配置流程说明
  • CCS20冗余架构设计原理:图解说明
  • 使用Miniconda为大模型推理服务配置负载均衡
  • Jupyter内核配置错误修复:确保Miniconda-Python3.10正确注册Python环境
  • Miniconda-Python3.10镜像在儿童教育大模型中的适配优化
  • Java Web 箱包存储系统系统源码-SpringBoot2+Vue3+MyBatis-Plus+MySQL8.0【含文档】
  • Miniconda-Python3.10环境下安装DGL进行图神经网络研究
  • 从Anaconda迁移到Miniconda-Python3.10:节省70%磁盘空间的方法
  • LTspice仿真错误排查技巧:常见报错通俗解释
  • 使用Miniconda实现PyTorch模型的金丝雀发布
  • 通过jflash实现安全启动配置:工业应用
  • PyTorch安装教程GPU版:Miniconda-Python3.10环境下一键部署深度学习模型
  • Miniconda-Python3.10镜像在诗歌生成大模型中的创意应用
  • Java SpringBoot+Vue3+MyBatis 项目申报管理系统系统源码|前后端分离+MySQL数据库
  • STM32波形发生器相位累加器实现:核心要点
  • Jupyter Notebook直连开发环境:Miniconda-Python3.10镜像使用图文教程
  • 使用Miniconda-Python3.10镜像批量部署百台服务器AI环境
  • Miniconda-Python3.10结合Gunicorn部署高可用模型服务