【Spring源码解析】组件注册-xml注册bean

前言

以前的spring-bean是通过xml注入bean的。

基础环境

  1. 创建一个 maven 项目
  2. 引入pom依赖
1
2
3
4
5
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.4</version>
</dependency>
  1. 创建一个简单对象
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/**
* @author cuishiying
* @date 2021-01-22
*/
public class Person {

private String name;
private Integer age;

public Person() {
}

public Person(String name, Integer age) {
this.name = name;
this.age = age;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Integer getAge() {
return age;
}

public void setAge(Integer age) {
this.age = age;
}

@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
  1. 在xml中注册bean
1
2
3
4
5
6
7
8
9
10
<?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 id="person" class="cn.idea360.bean.Person">
<property name="name" value="admin"></property>
<property name="age" value="17"></property>
</bean>
</beans>
  1. 测试
1
2
3
4
5
6
7
8
9
10
11
12
/**
* @author cuishiying
* @date 2021-01-22
*/
public class MainTest {

public static void main(String[] args) {
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
Person bean = (Person) applicationContext.getBean("person");
System.out.println(bean); // Person{name='admin', age=17}
}
}

最后

本篇到此结束,欢迎大家关注公众号【当我遇上你】。