前面的例子我们都是使用XML的bean定义来配置组件。在一个稍大的项目中,
通常会有上百个组件,如果这些这组件采用xml的bean定义来配置,
显然会增加配置文件的体积,查找及维护起来也不太方便。spring(Spring2.5以上的版本,包含2.5版)为
我们引入了组件自动扫描机制,它可以在类路径底下寻找标注了
@Component、 @Service、 @Controller、 @Repository 注解的类,
并把这些类纳入进spring容器中管理。它的作用和在xml文件中
使用bean节点配置组件是一样的。要使用自动扫描机制,我们需要打开
以下配置信息:
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-2.5.xsd">
          <context:component-scan base-package="cn.itcast"/>
</beans>
其中base-package为需要扫描的包(含子包)。

@Service用于标注业务层组件、
@Controller用于标注控制层组件 (如struts中的action)
@Repository用于标注数据访问组件,即DAO组件。
@Component 泛指组件,当组件不好归类的时候,
我们可以使用这个注解进行标注。

1、修改 XML 文件,代码如下:

 

可以查看该地址: http://blog.csdn.net/a9529lty/article/details/8251003 ,对 Spring 组件扫描<context:component-scan/> 有使用详解

2、分别修改 PresonDaoImpl 类 和 PresonServiceImpl 类,代码如下:

 

添加了一个 @Repository 注解。


3、修改单元测试类 ,代码如下:


这里或许会存在疑问 :

在 XML 文件中没有命名为 presonServiceImpl 的bean,而 (PresonService)ctx.getBean("presonServiceImpl") 是如何得到对象的? presonServiceImpl 是类名,并将首写字母小写,没有具体指明 bean 名称是会将这个默认为 bean 的名称,这是原则。如果要具体指明 bean 名称,那么要将 @Service 改为 @Service(“xxx”),例如:@Service(“personService”),则 personService 为 bean 名称。@Repository 也一样。

它们默认的作用范围是 singleton , 我们也可以紧随 @Service 之后添加 @Scope 来指明 bean 的作用域范围。@Scope 有 以下几个值:singleton 、prototype 、request、 session 。

具体使用方法如下: @Service("personService") @Scope("prototype"),不再做具体的测试。

4、如何指定初始化方法,如之前中 XML文件中的 init-method 属性?

在 PresonServiceImpl 类中的方法添加如下注解:


@PostConstruct 注解来指定方法是在初始化之后调用


@PreDestroy注解来指定方法是在销毁之前调用

posted on 2013-11-28 21:14  hwlsniper  阅读(351)  评论(0)    收藏  举报