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

Spring组件扫描<context:component-scan/>详解

2013-11-05 18:07 471 查看

引言

最近使用Spring,发现有很多依赖注入的内容,特别是DAO,百思不得其解,后来才知道是Spring的依赖注入。Spring可以批量将一个目录下所有的植入@Repository 注解或者@Service 注解的组件类一次性扫描出来。

事例

<?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:annotation-config />
<context:component-scan base-package=”com.eric.spring”>
</beans>


简单解释一下:

1、annotation-config是对标记了 Spring's @Required、@Autowired、JSR250's @PostConstruct、@PreDestroy、@Resource、JAX-WS's @WebServiceRef、EJB3's @EJB、JPA's @PersistenceContext、@PersistenceUnit等注解的类进行对应的操作使注解生效。

2、base-package为需要扫描的包(含所有子包),负责扫描那些类有注解。

官方解释

下面是引用spring framework开发手册中的一段话:

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已经能在持久化层中进行异常转换时被作为标记使用了。


接下来详细说明一下@Component、@Service、@Repository和@Controller的区别

@Component 泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注。

@Service 用于标注业务层组件

@Controller 用于标注控制层组件(如struts中的action)

@Repository 用于标注数据访问组件,即DAO组件

引用组件

在需要组件的地方,使用如下代码即可引用

@Resource
private ElevenDao elevenDao; //ElevenDao类是需要引用的组件
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: