本章主要简介说明通过xml配置文件,使用容器框架进行Bean管理。以及介绍多种数据类型(List/Set/Map/Array/Null)下,属性值的赋值方式。
- 使用maven构建项目,引入
spring-context
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
此仓库坐标将引入Spring开发中必备的jar包:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-30HPUHSk-1585497288956)(…/…/imgs/Spring开发必备jar包.png)]
- 配置beans.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"
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.xsd">
<bean id="heavent" class="com.heavent.spring.dao.User">
<property name="name" value="heavent" />
<property name="age" value="18" />
</bean>
<bean id="george" class="com.heavent.spring.dao.User">
<property name="name" value="george" />
<property name="age" value="24" />
</bean>
<!-- 属性为list/set/map/array赋值示例,以及将属性值设为null -->
<bean id="department" class="com.heavent.spring.dao.Department" >
<property name="code" value="financial_analysis" />
<property name="name" value="财经分析部门" />
<property name="minister" >
<null></null>
</property>
<property name="employee">
<set>
<ref bean="heavent"></ref>
<ref bean="george"></ref>
</set>
</property>
<property name="excellentEmployee">
<list>
<ref bean="heavent" />
<ref bean="george" />
</list>
</property>
<property name="leader">
<map>
<entry key="teamA" value-ref="heavent" />
<entry key="teamB" value-ref="george" />
</map>
</property>
<property name="teams" >
<array>
<value>teamA</value>
<value>teamB</value>
</array>
</property>
</bean>
</beans>
- 程序中调用
public class ApplicatoinMain {
public static void main(String[] args) {
System.out.println("-------------------- 通过xml配置的方式管理 ------------------------");
// 类编译目录下读取xml文件
ApplicationContext app = new ClassPathXmlApplicationContext("beans.xml");
// 查找添加bean的id为heavent的对象
User user = (User) app.getBean("heavent");
System.out.println(user.toString());
// 指定某个磁盘路径下读取xml文件
ApplicationContext app2 = new FileSystemXmlApplicationContext("C:\\Users\\Heavent\\Desktop\\github\\sample\\spring\\chapter01\\src\\main\\resources\\beans.xml");
Department department = (Department) app.getBean("department");
System.out.println(department.toString());
}