@Component 与 @Configuration 的区别¶
一、@Component¶
普通组件:
二、@Configuration¶
配置类:
@Configuration
public class AppConfig {
@Bean
public UserService userService() {
return new UserService();
}
}
三、核心区别:proxyBeanMethods¶
@Configuration 默认 proxyBeanMethods = true,即 Full 模式:
- 调用 @Bean 方法时,Spring 拦截,返回容器里的单例。
- 保证 @Bean 方法之间调用不会产生多个实例。
@Configuration
public class AppConfig {
@Bean
public A a() { return new A(b()); } // b() 返回容器里的单例
@Bean
public B b() { return new B(); }
}
@Component 没有这个代理,b() 就是普通方法调用,每次 new。
四、Lite 模式¶
@Configuration(proxyBeanMethods = false): - 不代理,启动快。 - @Bean 方法间不要互相调用。 - Spring Boot 大量用这种。
五、总结¶
| @Component | @Configuration | |
|---|---|---|
| @Bean 方法 | 普通方法 | 被代理 |
| 单例保证 | ❌ | ✅ |
| 启动速度 | 快 | 慢(代理) |
| 用途 | 组件 | 配置 |
Spring Boot
Spring Boot 自动配置类大多是 @Configuration(proxyBeanMethods=false),因为不需要互相调用,启动快。