通过前两篇文章我们可以发现有两大类比较使用的注入方式,一类是完全通过XML文件配置(bean的声明管理和注入都在XML中完成)的方式来注入,另外一类是在XML文件中配置bean将它们纳入Spring容器进行管理,然后在Java代码中使用注解的方式进行注入,这种方式稍微方便一点,但是,懒惰是人类的天性,我们能不能连在XML文件中声明bean这一步都去掉呢?答案是可以的,在文件中声明bean无非也是把组件交给Spring容器进行管理,其实Spring提供了一种更加高端的做法,那就是通过自动扫描的方式,把组件纳入到Spring容器进行管理。
先来看看项目结构(假设操作的是Department对象):
数据访问层接口:
/**
* 数据访问层接口
* @author Liao
*/
public interface IDepartmentDao {
/**
* 测试方法
*/
public void test();
}
数据访问层接口实现类:
@Repository
public class DepartmentDaoImpl implements IDepartmentDao {
@Override
public void test() {
System.out.println("您调用了测试方法");
}
}
注:@Repository用于表组数据访问组件,即Dao组件。
业务逻辑层接口:
/**
* 业务逻辑层接口
* @author Liao
*/
public interface IDepartmentService {
/**
* 测试方法
*/
public void test();
}
业务逻辑层接口实现类:
@Service
public class DepartmentServiceImpl implements IDepartmentService {
@Resource
private IDepartmentDao departmentDao;
@Override
public void test() {
/*通过数据访问层进行方法调用*/
departmentDao.test();
}
}
注:@Service用于标注业务组件。
XML配置文件要有所改变:
<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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!-- 定义自动扫描的包的范围 -->
<context:component-scan base-package="com.lixue.dao.impl,com.lixue.service.impl" />
</beans>
注:base-package属性声明了自动扫面的包(含子包)。
扫面注解介绍:
1.@Service用于标注业务层组件。
2.@Controller用于标注控件层组件(如struts2中的action,在整合Spring和struts2的时候也可以不用这个属性,因为有一个struts2-spring-plugin.jar包可以使得action自动纳入Spring容器管理)。
3.@Repository用于标注数据访问层组件,即Dao组件。而@Component泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注。
4.Scope用于指定scope作用域(用在类上)。
5.@PostConstruct用于指定初始化方法(用在方法上)
6.PreDestory用于指定销毁方法(用在方法上)
测试类:
public class DepartmentTest {
public static void main(String[] args) {
/*初始化Spring容器*/
ApplicationContext ctx = new ClassPathXmlApplicationContext(new String[]{"department-beans.xml"});
/*ctx.getBean("departmentServiceImpl")获取Bean*/
IDepartmentService departmentService = (IDepartmentService) ctx.getBean("departmentServiceImpl");
departmentService.test();
}
}