@Bean
作用于方法,声明该方法产生的对象为bean,由spring Ioc统一初始化、装配、管理。该方法一般置于@configuration作用的类中。
@Configuration
作用于类,该类通常包含若干由@Bean修饰的方法。@Configuration表明该类由Spring Ioc统一管理、定义类,并提供服务请求、配置依赖关系。
@Component
作用于类,使该类中的bean能够在classpath 扫描中被探测到,@Configuration的功能大于@Component, @Component的功能大于@Bean
摘抄自stackoverflow的一段话:很有道理,不翻译了
@Componentand@Beando two quite different things, and shouldn't be confused.
@Component(and@Serviceand@Repository) are used to auto-detect and auto-configure beans using classpath scanning. There's an implicit one-to-one mapping between the annotated class and the bean (i.e. one bean per class). Control of wiring is quite limited with this approach, since it's purely declarative.
@Beanis used to explicitly declare a single bean, rather than letting Spring do it automatically as above. It decouples the declaration of the bean from the class definition, and lets you create and configure beans exactly how you choose.
参考链接
Spring框架中的@Bean与@Component注解解析
本文详细解释了Spring框架中@Bean和@Component注解的区别。@Bean用于明确声明一个单例bean,允许自定义初始化和配置。而@Component则是用于类的自动扫描和bean的声明,适用于简单的一对一映射。@Configuration则用于定义配置类,包含多个@Bean方法,提供更灵活的依赖注入控制。
1167

被折叠的 条评论
为什么被折叠?



