由Spring全权管理的“对象”容器
普通的对象:自己new自己管理
通过注解 + 自动扫描的方式,让 Spring 自动发现并注册 Bean。
| 注解 | 语义 | 典型场景 |
|---|---|---|
@Component |
通用组件 | 工具类、通用服务 |
@Service |
业务逻辑层 | Service 层 |
@Repository |
数据访问层 | DAO / Mapper 层 |
@Controller / @RestController |
控制器层 | Web 接口层 |
// 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);
}
}
Spring 启动
│
▼
扫描指定包路径下所有类
│
▼
发现 @Component / @Service / @Repository / @Controller
│
▼
自动创建实例并注册到 IoC 容器
│
▼
Bean 可用,支持 @Autowired 注入
通过 @Configuration + @Bean 手动声明 Bean 的创建逻辑。
@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");
}
}
Spring 启动
│
▼
发现 @Configuration 类
│
▼
执行所有 @Bean 方法
│
▼
将返回对象注册到 IoC 容器
│
▼
Bean 可用,支持 @Autowired 注入
┌──────────────┬─────────────────────┬──────────────────────┐
│ 维度 │ 组件扫描 │ 配置类 @Bean │
├──────────────┼─────────────────────┼──────────────────────┤
│ 控制粒度 │ 低,自动发现 │ 高,精确控制 │
│ 适用对象 │ 自己写的类 │ 第三方库的类 │
│ 创建逻辑 │ 默认构造函数 │ 完全自定义 │
│ 代码侵入性 │ 需要加注解 │ 无侵入,类不用改动 │
│ 集中管理 │ 分散在各类中 │ 集中在一个配置类 │
│ 条件装配 │ @Conditional 系列 │ 同样支持,更灵活 │
└──────────────┴─────────────────────┴──────────────────────┘
// 自己写的业务代码,直接加注解即可
@Repository
public class UserDao {
public User find(Long id) { ... }
}
@Service
public class UserService {
@Autowired
private UserDao userDao; // 自动注入
}
@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,走配置类,灵活可控
两者并不冲突,实际项目中通常是混合使用的。
暂无评论,欢迎第一个留言。
评论