什么是Spring Bean

发布于 更新于 243 字 2 分钟阅读

#什么是Spring Bean

由Spring全权管理的“对象”容器

普通的对象:自己new自己管理

#Spring Bean 的两种常见定义方式

#一、组件扫描(Component Scanning)

通过注解 + 自动扫描的方式,让 Spring 自动发现并注册 Bean。

#核心注解

注解 语义 典型场景
@Component 通用组件 工具类、通用服务
@Service 业务逻辑层 Service 层
@Repository 数据访问层 DAO / Mapper 层
@Controller​ / @RestController 控制器层 Web 接口层

#示例

Java
// 1. 标注注解 → 声明"我是一个 Bean"
@Service
public class UserService {

    public User findById(Long id) {
        // ...
    }
}

// 2. 配置扫描路径(Spring Boot 自动处理)
@SpringBootApplication  // 内含 @ComponentScan
public class MyApp {
    public static void main(String[] args) {
        SpringApplication.run(MyApp.class, args);
    }
}

#工作流程

Text
Spring 启动
    │
    ▼
扫描指定包路径下所有类
    │
    ▼
发现 @Component / @Service / @Repository / @Controller
    │
    ▼
自动创建实例并注册到 IoC 容器
    │
    ▼
Bean 可用,支持 @Autowired 注入

#二、配置类(Java Config / @Bean)

通过 @Configuration​ + @Bean手动声明 Bean 的创建逻辑。

#示例

Java
@Configuration
public class AppConfig {

    @Bean
    public DataSource dataSource() {
        HikariDataSource ds = new HikariDataSource();
        ds.setUrl("jdbc:mysql://localhost:3306/mydb");
        ds.setUsername("root");
        ds.setPassword("123456");
        return ds;
    }

    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }

    // 方法名就是 Bean 的名称,也可以自定义
    @Bean("myCache")
    public CacheManager cacheManager() {
        return new ConcurrentMapCacheManager("users");
    }
}

#工作流程

Text
Spring 启动
    │
    ▼
发现 @Configuration 类
    │
    ▼
执行所有 @Bean 方法
    │
    ▼
将返回对象注册到 IoC 容器
    │
    ▼
Bean 可用,支持 @Autowired 注入

#三、核心对比

Text
┌──────────────┬─────────────────────┬──────────────────────┐
│     维度      │   组件扫描            │   配置类 @Bean         │
├──────────────┼─────────────────────┼──────────────────────┤
│  控制粒度     │  低,自动发现          │  高,精确控制           │
│  适用对象     │  自己写的类            │  第三方库的类           │
│  创建逻辑     │  默认构造函数          │  完全自定义             │
│  代码侵入性   │  需要加注解            │  无侵入,类不用改动       │
│  集中管理     │  分散在各类中          │  集中在一个配置类         │
│  条件装配     │  @Conditional 系列    │  同样支持,更灵活         │
└──────────────┴─────────────────────┴──────────────────────┘

#四、典型应用场景

#✅ 用组件扫描的场景

Java
// 自己写的业务代码,直接加注解即可
@Repository
public class UserDao {
    public User find(Long id) { ... }
}

@Service
public class UserService {
    @Autowired
    private UserDao userDao;  // 自动注入
}

#✅ 用 @Bean 的场景

Java
@Configuration
public class ThirdPartyConfig {

    // 第三方库的类,你无法在源码上加 @Component
    @Bean
    public ModelMapper modelMapper() {
        ModelMapper mapper = new ModelMapper();
        mapper.getConfiguration()
              .setMatchingStrategy(MatchingStrategies.STRICT);
        return mapper;
    }

    // 需要复杂初始化逻辑的 Bean
    @Bean
    public ObjectMapper objectMapper() {
        ObjectMapper om = new ObjectMapper();
        om.registerModule(new JavaTimeModule());
        om.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        om.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        return om;
    }
}

#五、总结一句话

  • 自己写的类 → 加 @Component​ 系列注解,走组件扫描,简单省事
  • 第三方类 / 需要复杂初始化 → 用 @Configuration​ + @Bean​,走配置类,灵活可控

两者并不冲突,实际项目中通常是混合使用的。

zxb的博客

评论

还没有评论,来说点什么吧。

评论经发布者审核后公开
46 篇文档

文档树

14 个章节

本文目录

搜索文档

输入关键词,立即搜索当前分享。