您的位置:首页 > 编程语言 > Java开发

第四章 Spring进阶-自动扫描和管理Bean

2010-05-06 13:23 225 查看
第四章 Spring进阶-自动扫描和管理Bean
徒弟:师傅,好累呀,我今天配置了几十个bean,快不行啦!
师傅:up,没有那么弱吧?先磨炼一下,再告诉你秘诀!

徒弟问,要自己配置bean,如果有成千上万的类,岂不是要他配置到死翘翘,师傅,有没有其他办法管理bean呀,如果确定需要配置一个bean,最好我写完接口的实现类,就配置完毕,别再让我折腾配置文件了?

其实,到目前为止大多数例子都使用XML来指定配置元数据,这些元数据会生成Spring容器中的每个BeanDefinition。 即使上一章A利用@Resource解决了注入问题, bean还是需要在xml中显式定义。因此本章会介绍一种方法,通过扫描classpath并匹配过滤器来隐式地检测候选组件 (candidate components)。

补充:
具体可以参考:参考Spring Framework开发手册 3.12. 对受管组件的Classpath扫描

徒弟看完文档之后,立马醒悟了,做了以下几步:
1、修改BookServiceImpl,增加, 如图所示定义:



这个时候提示,需要引入包:
import org.springframework.stereotype.Service;

2、徒弟很聪明,同样修改了DAO
@Service("bookDAO")
public class BookDAOImpl implements BookDAO

2、修改beans.xml
<!--<context:annotation-config/>
 <bean id="bookService" class="com.netease.lee.service.impl.BookServiceImpl"/>
 <bean id="bookDAO" class="com.netease.lee.dao.impl.BookDAOImpl"/>
 -->
 <context:component-scan base-package="com.netease.lee"/>
3、运行测试用例,居然成功了:



这里需要更正一个概念,第二步中@Service("bookDAO")
根据Spring Framework中的建议:
从Spring 2.0开始,引入了@Repository注解, 用它来标记充当储存库(又称 Data Access Object或DAO)角色或典型的类。
Spring 2.5引入了更多典型化注解(stereotype annotations): @Component、@Service和 @Controller。 @Component是所有受Spring管理组件的通用形式; 而@Repository、@Service和 @Controller则是@Component的细化, 用来表示更具体的用例(例如,分别对应了持久化层、服务层和表现层)。也就是说, 你能用@Component来注解你的组件类, 但如果用@Repository、@Service 或@Controller来注解它们,你的类也许能更好地被工具处理,或与切面进行关联。 例如,这些典型化注解可以成为理想的切入点目标。当然,在Spring Framework以后的版本中, @Repository、@Service和 @Controller也许还能携带更多语义。如此一来,如果你正在考虑服务层中是该用 @Component还是@Service, 那@Service显然是更好的选择。同样的,就像前面说的那样, @Repository已经能在持久化层中进行异常转换时被作为标记使用了。
因此,修改为:
@Repository("bookDAO")
public class BookDAOImpl implements BookDAO
这样子,思路更加清晰了,其他开发人员一看,就知道意思了。
徒弟检查了配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<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="com.netease.lee"/>
</beans>
发觉,瘦身成功!终于可以很爽快了! 本文出自 “lee” 博客,请务必保留此出处http://jooben.blog.51cto.com/253727/311069
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: