@Bean, @Component, @Configuration简析

@Bean

作用于方法,声明该方法产生的对象为bean,由spring Ioc统一初始化、装配、管理。该方法一般置于@configuration作用的类中。

@Configuration

作用于类,该类通常包含若干由@Bean修饰的方法。@Configuration表明该类由Spring Ioc统一管理、定义类,并提供服务请求、配置依赖关系。

@Component

作用于类,使该类中的bean能够在classpath 扫描中被探测到,@Configuration的功能大于@Component, @Component的功能大于@Bean

摘抄自stackoverflow的一段话:很有道理,不翻译了

@Component and @Bean do two quite different things, and shouldn't be confused.

@Component (and @Service and @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.

@Bean is 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.

参考链接

explanation in stackoverflow

@Component vs @Bean

Component annotation

你可能感兴趣的:(spring,spring,component,configuration,bean)