Spring的配置流程
导包
导入基本的核心包
- spring-beans-4.3.8.RELEASE.jar
- spring-context-4.3.8.RELEASE.jar
- spring-core-4.3.8.RELEASE.jar
- spring-expression-4.3.8.RELEASE.jar
- commons-logging-1.2.jar
- log4j-1.2.17.jar
导入约束
两种方式:
1. 导入约束文件
2. 去官方文档复制
第一种, 导入约束文件
- 在工具配置中导入约束文件
- 到desgin模式中导入约束
第二种, 去官方文档复制
- 从下载的压缩包中打开xsd-configuration.html文件
..\spring-framework-4.3.8.RELEASE-dist\spring-framework-4.3.8.RELEASE\docs\spring-framework-reference\html\xsd-configuration.html
- 搜索xmlns来查看示例的约束,然后复制
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- bean definitions here -->
</beans>
创建JavaBean
- Interface
/**
* ICustomer接口
*/
public interface ICustomerDao {
/**
* 保存客户
*/
void saveCustomer();
}
- Impl
/**
* ICustomerDao的实现类
*/
public class CustomerDaoImpl implements ICustomerDao {
/* (non-Javadoc)
* @see com.dao.ICustomerDao#saveCustomer()
*/
@Override
public void saveCustomer() {
System.out.println("save Customer Success!");
}
}
书写配置文件
- 配置文件的名字可以随意写,可以选择规范 applicationContext.xml 名字
<?xml version="1.0" encoding="UTF-8"?>
<!-- 导入schema
约束的位置在:
..\spring-framework-4.3.8.RELEASE\docs\spring-framework-reference\html\xsd-configuration.html
文件中。
注意:
导入schema约束,并且建议将spring-beans.xsd,增加使用的大版本信息:spring-beans-4.0.xsd
-->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
<!-- 配置客户dao实现类对象,说明:
bean标签:配置javaBean对象
id属性:指定对象的唯一标识名称
class属性:指定类的全限定类名称(包名称+类名称) -->
<bean id="customerDao" class="com.dao.impl.CustomerDaoImpl"></bean>
</beans>
测试类
- “classpath:”表示在类的根路径下,是一个标识符,加上是使用习惯。也可以不加。
public class Client {
/**
* ApplicationContext接口:
* 1.它就相当于一个大工厂,提供了根据配置文件中的id属性值,获取对象
*
* 2.实现类:
* ClassPathXmlApplication类,从类的根路径下加载配置文件(企业项目开发中,使用较多)
* FileSystemXmlApplication类,从文件系统(磁盘)上加载配置文件
* @param args
*/
public static void main(String[] args) {
// 1.创建ClassPathXmlApplication对象
// 注意这里的"classpath:"表示在类的根路径下,是一个标识符,加上是使用习惯。也可以不加。
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:appliactionContext.xml");
// 2.从context中,获取客户dao对象
// getBean方法:获取bean对象
// name参数:配置文件中id属性值
CustomerDao customerDao = (CustomerDao) context.getBean("customerDao");
// 3.调用方法执行
customerDao.saveCustomer();
}
}
- 结果输出
save Customer Success!