【Spring入门】13.通过注解配置Bean

在 classpath 中扫描组件

组件扫描(component scanning):  Spring 能够从 classpath 下自动扫描, 侦测和实例化具有特定注解的组件.


特定组件包括:
@Component: 基本注解, 标识了一个受 Spring 管理的组件
@Respository: 标识持久层组件
@Service: 标识服务层(业务层)组件
@Controller: 标识表现层组件


 

例子如下:

一、包的部署

1.新建包:com.spring.beans.annotation

                      包下新建类TestObject、Main

              com.spring.beans.annotation.controller

                      包下新建类UserController

              com.spring.beans.annotation.service

                      包下新建类UserService

              com.spring.beans.annotation.repository

                      包下新建类UserRepository

【Spring入门】13.通过注解配置Bean

2.为TestObject,UserController, UserRepositoryImpl, UserService分别打上注解@Component, @Controller, @Repository, @Service ,其中UserRepositoryImpl实现接口UserRepository。

其中对userRepositoryimpl 添加的注解@Repository的value值是"Repository"以表示Repository即该组件的名称

【Spring入门】13.通过注解配置Bean

 

 二、新建xml配置文件,命名为beans-annotation.xml(xml文件存放在src包中)

添加 context:component-scan 标签,base-package设置为三个服务的父包,一次让AOP容器检测所有的注解

【Spring入门】13.通过注解配置Bean

 

三、编辑Main测试配置效果

【Spring入门】13.通过注解配置Bean

对于扫描到的组件, Spring 有默认的命名策略: 使用非限定类名, 第一个字母小写. 也可以在注解中通过 value 属性值标识组件的名称

在这里的的体现是调用ctx.getBean()时括号内的名字

 

结果是成功的:

【Spring入门】13.通过注解配置Bean

 

使用@Autowired自动装配Bean

@Autowired注解自动装配具有兼容类型的单个bean属性

例子:

我想要在UserController中调用UserService.add():
【Spring入门】13.通过注解配置Bean

在 UserService中调用UserRepository.save():

【Spring入门】13.通过注解配置Bean

Mian中调用UserController.execute()测试:

【Spring入门】13.通过注解配置Beanjie'g

 结果发现是失败的,控制台显示空指针异常。

【Spring入门】13.通过注解配置Bean

所以@Autowired的作用在此体现了 :

在UserController,UserService的构造器or普通字段or一切具有参数的方法前添加@Autowired注解后,IOC容器将自动在xml所指定的包中搜索注解以下的代码出现的Bean并装配:

【Spring入门】13.通过注解配置Bean

结果是成功的。