最近使用Spring,发现有不少依赖注入的内容,特别是DAO,百思不得其解,后来才知道是Spring的依赖注入。Spring能够批量将一个目录下全部的植入@Repository 注解或者@Service 注解的组件类一次性扫描出来。 spring
<?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>
简单解释一下: 工具
一、annotation-config是对标记了 Spring's @Required、@Autowired、JSR250's @PostConstruct、@PreDestroy、@Resource、JAX-WS's @WebServiceRef、EJB3's @EJB、JPA's @PersistenceContext、@PersistenceUnit等注解的类进行对应的操做使注解生效。 ui
二、base-package为须要扫描的包(含全部子包),负责扫描那些类有注解。 spa
下面是引用spring framework开发手册中的一段话: .net
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的区别 code
@Component 泛指组件,当组件很差归类的时候,咱们能够使用这个注解进行标注。 component
@Service 用于标注业务层组件 xml
@Controller 用于标注控制层组件(如struts中的action) 开发
@Repository 用于标注数据访问组件,即DAO组件 get
在须要组件的地方,使用以下代码便可引用
@Resource private ElevenDao elevenDao; //ElevenDao类是须要引用的组件