xml配置初级使用
1.搭建Maven项目,并在pom引入依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.19.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>RELEASE</version>
<scope>test</scope>
</dependency>
2.容器的实例化和使用
-
创建Spring的配置文件 spring_ioc_base.xml
<?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"> </beans>
-
创建单元测试,测试Spring项目启动加载配置文件
-
ApplicationContext详解
创建spring上下文,加载所有的bean
- ClassPathXmlApplicationContext 根据项目路径的xml配置实例化spring容器
- FileSystemXmlApplicationContext 根据磁盘路径的xml配置实例化spring容器
- AnnotationConfigApplicationContext 根据javaConfig配置实例化spring容器
对象在Spring容器创建完成的时候就已经创建完成,不是需要用的时候才创建。
3. 创建User对象
public class User {
private Integer id;
private String name;
private Integer age;
private String address;
private String job;
getter and setter...
}
4. bean的使用
在xml文件中为User对象配置一个bean,使用标签
<!--配置bean-->
<!--默认使用无参构造函数-->
<bean class="com.lazy.entity.User" id="user" />
<!--使用name设置别名,可以使用 空格 , ;-->
<bean class="com.lazy.entity.User" id="user1" name="user2 user3,user4;user5"/>
<!--配置bean别名-->