一、问题说明
之前写了一篇博客Spring源码阅读之编译带源码的jar包,这样操作的目的是想在新建的项目里能调试自己写过注释的源码。
后来我发现其实有个更为简便的方法,直接在本地已经导入的spring-framework源码中创建一个gradle模块,然后引入你想测的模块就可以了
二、解决方法
举个例子:
我想断点调试看下spring是如何创建bean的(getBean方法),用如下一段代码
@Test
public void test() {
ApplicationContext ac = new ClassPathXmlApplicationContext("com/kittycoder/simpledemo/spring-student.xml");
Teacher teacher = (Teacher) ac.getBean("teacher");
System.out.println(teacher);
}
具体步骤如下:(如何搭建spring源码阅读环境可以参看 https://blog.csdn.net/u010999809/article/details/90444714)
1. 右键新建一个module
2.修改配置
(1)spring-framework根目录下的settings.gradle中应该会多一行(idea替你加的),里面已经加进去了这个就不用操作了
(2)刚才创建的spring-lsc-test模块,gradle配置文件用的是默认名字build.gradle,你也可以更改成spring里定义好的名字(就叫spring-lest-test.gradle)
(3) idea里新建好的gradle配置文件里会夹带一些用不到的配置,参考下spring其他模块的gradle配置,我直接把spring-lsc-test.gradle改成下面的样子:
经过上面两步,配置就搞定了
三、开始调试
这里简单贴下目录结构以及相关代码,便于各位重现。
这个结构也是spring源码里各模块在编写测试的时候一种分模块方式,我这里稍微借鉴了一下
Student.java
package com.kittycoder.simpledemo.po;
/**
* Created by shucheng on 2019-6-29 下午 20:47
*/
public class Student {
private Integer id;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Teacher.java
package com.kittycoder.simpledemo.po;
/**
* Created by shucheng on 2019-6-29 下午 21:04
*/
public class Teacher {
private Student student;
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
}
SimpleDemoTest.java
package com.kittycoder.simpledemo;
import com.kittycoder.simpledemo.po.Teacher;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* Created by shucheng on 2019-6-29 下午 20:42
*/
public class SimpleDemoTest {
@Test
public void test() {
ApplicationContext ac = new ClassPathXmlApplicationContext("com/kittycoder/simpledemo/spring-student.xml");
Teacher teacher = (Teacher) ac.getBean("teacher");
System.out.println(teacher);
}
}
spring-student.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 https://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<bean id="teacher" class="com.kittycoder.simpledemo.po.Teacher">
<property name="student" ref="student"/>
</bean>
<bean id="student" class="com.kittycoder.simpledemo.po.Student"></bean>
</beans>