Spring 环境搭建
- 导入 jar
四个核心包一个日志包(commons-logging) - 配置文件——在 src 下新建 applicationContext.xml
①文件名称和路径自定义
②记住 Spring 容器 ApplicationContext,applicationContext.xml 配
置的信息最终存储到了 AppliationContext 容器中
③spring 配置文件是基于 schema
1 schema 文件扩展名.xsd
2 把 schema 理解成 DTD 的升级版
注:比 DTD 具备更好的扩展性
每次引入一个 xsd 文件是一个 namespace(xmlns)
④配置文件中只需要引入基本 schema
通过bean/ 标签 创建对象(用全路径)
默认配置文件被加载时创建对象
<?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/sc
hema/beans
http://www.springframework.org/schema/beans/spring-be
ans.xsd">
id 表示获取到对象标识,其中class 创建哪个类的对象,id随意
<bean id="peo" class="com.youdian.pojo.People"/> </beans>
- 编写测试方法
①getBean(“ bean 标签id值”,返回值类型);如果没有第二个参数,默认是 Object
②getBeanDefinitionNames(),Spring 容器中目前所有管理的所有对象
配置文件被加载,类立即被创建
ApplicationContext ac = new
ClassPathXmlApplicationContext("applicationContext.xml");
People people = ac.getBean("peo",People.class); //自动转换成你传入的类型
System.out.println(people);
// String[] names = ac.getBeanDefinitionNames(); //管理的类的对象
// for (String string : names) {
// System.out.println(string);
//}