创建新模块
在本地的spring源码项目上,新建一个spring-demo模块,用于后续的源码学习调试做准备.
前置准备工作见:https://www.jianshu.com/p/9be898e39856
如下图所示创建spring-demo模块
在新的模块上,会自动创建文件build.gradle.kts
,以及在原有的settings.gradle
文件中自动添加一行include 'spring-demo'
修改配置
-
将
settings.gradle
文件中自动添加的include 'spring-demo'
配置,挪到rootProject.name = "spring"
这一行的上面.
修改
build.gradle.kts
文件的名称为spring-demo.gradle
(项目模块名称.gradle),并且将原有的内容修改为
description = "spring-demo"
dependencies {
compile(project(":spring-context"))
}
编写demo
新建Student类
public class Student {
private String id;
private String stuName;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getStuName() {
return stuName;
}
public void setStuName(String stuName) {
this.stuName = stuName;
}
}
新建spring-demo.xml
在resources路径下新建spring-demo.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">
<!-- 这里的class路径注意替换成自己的路径 -->
<bean id="student" class="jc.demo.Student">
<property name="id" value="1234"/>
<property name="stuName" value="张三"/>
</bean>
</beans>
修改main方法
修改main方法,并运行
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("classpath*:spring-demo.xml");
Student student = (Student) context.getBean("student");
System.out.println("-------------------");
System.out.println("student_id:" + student.getId());
System.out.println("student_name:" + student.getStuName());
System.out.println("-------------------");
}
}