spring之在classpath中扫描组件(2)
----------
自动扫描组件
spring2.5提供了强大的组件扫描特性,它能够从classpath里自动扫描、侦测和实例化组件。默认情况下,Spring能够侦测到所有具有特定注解的组件。基本的注解类型是@Component,它标识了一个受Spring管理的组件。
如例,可以在SequenceDaoImpl类里使用该注解。
package com.apress.springrecipes.sequence;
import org.springframework.stereotype.Component;
@Component
public class SequenceDaoImpl implements SequenceDao{
...
}
如例,同样,也可以为SequenceService类加上该注解,这样Spring就会自动侦测到它。另外,给它的DAO字段加上@Autowired注解,这样Spring会根据类型自动装配该属性。
package com.apress.springrecipes.sequence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class SequenceService{
@Autowired
private SequenceDao sequenceDao;
...
}
当在组件类上使用了该特定注解之后,可以声明单独的XML元素---<context:component-scan>,让Spring扫描这些组件。在这个元素里,需要为组件扫描指定包。指定完毕后,Spring将扫描被指定的包以及它所有的子包。当存在多个需要扫描的包时,可以使用逗号分隔它们。
请注意,这个元素还会注册一个AutowiredAnnotationBeanPostProcessor实例,该实例能够自动装配具有
@Autowired注解的属性。
<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.springframewrok.org/schema/context/spring-context-2.5.xsd"> <context:component-scan base-package="com.apress.springrecipes.sequence"/> ... </beans>
@Component注解标识了一般用途的组件,实际上,还存在其他特定的注解,这些注解用于标识位于不同层中的组件。首先,@Repostiory标识了处于持久层中的DAO组件。
package com.apress.springrecipes.sequence;
import org.springframework.stereotype.Repository;
@Repository
public class SequenceDaoImpl implements SequenceDao{
...
}
接下来,@Service标识了处于服务层的服务组件。
package com.apress.springrecipes.sequence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class SequenceService{
@Autowired
private SequenceDao sequenceDao;
....
}
另外还有一个@Controller注解,标识了处于表现层的控制器组件。