spring3.X为我们引入了组件自动扫描机制,它可以在classPath路径底下寻找标注了@Component、@Service、@Controller、@Repository注解的类,并把这些类纳入进spring容器中管理。
首先说明一下注解的含义:
@Service用于标注业务层组件。
@Controller用于标注控制层组件(如struts中的action)。
@Repository用于标注数据访问组件,即DAO组件。
@Component泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注。
使用Spring自动装备机制要在XML文件中配置以下信息:
一、引入context的命名空间
<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"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd" default-lazy-init="true">
二、在配置文件中添加context:component-scan标签
<context:component-scan base-package="com.***.controller" />
这样就可以在文件中使用注解了,以@Resource为例,有两种实现方式:
一、
<pre name="code" class="java"> //用在属性上
@Resource(name = "newsService")
private NewsService newsService;
二、
//用于属性的set方法上
@Resource(name="newsDao")
public void setNews(NewsDao newsDao) {
this.newsDao = newsDao;
}
前者默认取字段的名称作为bean名称寻找依赖对象,后者默认取属性名作为bean名称寻找依赖对象。