spring boot 注解 @bean
在 Java 中,@Bean
是 Spring Framework 的核心注解之一,用于将方法的返回值声明为一个由 Spring 容器管理的对象(即一个 “Bean”)。它是 基于 Java 配置(@Configuration
类)的关键组成部分,替代了传统的 XML 配置方式。
1. 基本用法
在带有 @Configuration
注解的类中,使用 @Bean
标注方法,Spring 会将该方法的返回值注册为 Bean:
@Configuration
public class AppConfig {@Beanpublic MyService myService() {return new MyServiceImpl(); // 实例由 Spring 管理}
}
• Bean 名称:默认使用方法名(如 myService
),也可通过 @Bean(name = "customName")
指定。
• 依赖注入:方法参数会自动注入其他 Bean(无需显式 @Autowired
):
@Bean
public DataSource dataSource() {return new HikariDataSource();
}@Bean
public JdbcTemplate jdbcTemplate(DataSource dataSource) {return new JdbcTemplate(dataSource); // 自动注入 DataSource
}
2. 常见场景
(1)第三方库的 Bean
当需要集成非 Spring 管理的类(如外部库)时:
@Bean
public RestTemplate restTemplate() {return new RestTemplate();
}
(2)条件化注册
结合 @Conditional
系列注解,按条件创建 Bean:
@Bean
@ConditionalOnProperty(name = "feature.enabled", havingValue = "true")
public FeatureService featureService() {return new FeatureService();
}
(3)初始化/销毁方法
指定 Bean 的生命周期回调:
@Bean(initMethod = "init", destroyMethod = "cleanup")
public ResourcePool resourcePool() {return new ResourcePool();
}
3. 高级特性
(1)作用域(Scope)
通过 @Scope
指定 Bean 的作用域(默认单例):
@Bean
@Scope("prototype") // 每次请求创建新实例
public PrototypeBean prototypeBean() {return new PrototypeBean();
}
(2)懒加载(Lazy Initialization)
延迟初始化 Bean,直到首次被使用时:
@Bean
@Lazy
public ExpensiveBean expensiveBean() {return new ExpensiveBean(); // 启动时不立即创建
}
(3)Primary/Qualifier
解决多个同类型 Bean 的冲突:
@Bean
@Primary // 优先注入
public DataSource primaryDataSource() { ... }@Bean
public DataSource secondaryDataSource() { ... }
4. 与 @Component
的区别
特性 | @Bean | @Component |
---|---|---|
定义方式 | 在 @Configuration 类的方法上 | 直接标注在类上 |
适用场景 | 更适合第三方库或复杂初始化逻辑 | 适合自定义业务组件(如 Service) |
灵活性 | 可动态生成实例(如条件化 Bean) | 固定类声明 |
5. 常见问题
• Q: @Bean
方法是否必须返回对象?
A: 是,且每次调用默认返回同一实例(单例),除非标注 @Scope("prototype")
。
• Q: 如何解决循环依赖?
A: 优先通过构造函数注入,或使用 @Lazy
延迟加载。
• Q: 能否在 @Component
类中使用 @Bean
?
A: 可以,但推荐仅在 @Configuration
中使用(Spring 会代理确保单例)。
如果需要更具体的例子或深入某个场景,可以告诉我! 😊
类上加这几个注解 和@bean 一样
@bean 的作用主要还是 添加依赖中的类到容器中
@ConfigurationProperties 使用配置文件properties 中的 值