这两个可以理解为人为主动向 spring IOC 中注册对象。
一般来说,spring IOC 的注册和使用流程如下。
- 使用
@component @Repository @Service @Controller注册相关Bean - 使用
@Autowired @Qualifier @Resource
但是,借助 @Configuration @Bean 可以进行人为注册,具体看下面例子。
编写一个接口类
1 | public interface ArticleService { |
实现接口类
实现两个接口类。
第一个
1 | public class ArticleServiceImpl implements ArticleService { |
第二个
1 | public class ArticleService2Impl implements ArticleService { |
注意,这两个接口类,都没有用 @component @Repository @Service @Controller 修饰
人为注册 Bean
1 |
|
使用 Bean
1 | @RestController |
上面的 @Resource(name = "articleServiceImpl") 中的 articleServiceImpl,就是 人为注册 bean 中的第一个 Bean。
Bean 和 @component @Repository @Service @Controller 区别
位置上
@Component: 作用于类上,告知Spring,为这个类创建Bean。通常是通过类路径扫描来自动侦测以及自动装配到Spring容器中。(@Controller、@Service、@Repository)。@Bean:主要作用于方法或者注解上,告知Spring,这个方法会返回一个对象,且要注册在Spring的上下文中。通常方法体中包含产生Bean的逻辑。
使用
- 作用都是一样的,都是注册
bean到Spring容器中。 - 引用第三方库中的类需要装配到
Spring容器时,则只能通过@Bean来实现。