一、 Spring Auto Scanning Components —— 自动扫描组件
通常你可以在xml配置文件中,声明一个bean或者component,然后Spring容器会检查和注册你的bean或component。实际上,Spring支持自动扫描bean或component,你可以不必再在xml文件中繁琐的声明bean,Spring会自动扫描、检查你指定包的bean或component。
以下列举一个简单的Spring Project,包含了Customer、Service、DAO层,让我们来看一下手动配置和自动扫描的不同。
1. Declares Components Manually——手动配置component
先看一下正常手动配置一个bean
DAO层,CustomerDAO.java如下:
packagecom.lei.customer.dao;public classCustomerDAO
{
@OverridepublicString toString() {return "Hello , This is CustomerDAO";
}
}
Service层,CustomerService.java如下:
packagecom.lei.customer.services;importcom.lei.customer.dao.CustomerDAO;public classCustomerService
{
CustomerDAO customerDAO;public voidsetCustomerDAO(CustomerDAO customerDAO) {this.customerDAO =customerDAO;
}
@OverridepublicString toString() {return "CustomerService [customerDAO=" + customerDAO + "]";
}
}
配置文件,Spring-Customer.xml文件如下:
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
运行如下代码,App.java如下:
pack