源码下载好了,如何去引用呢?接下来我们创建一个自己的项目去探究一下。
1.创建spring-framework下模块【spring-demo】
右击spring-framework->module->new module,具体选择如下
2.创建一个java类去查看当前项目是否正常运行
package com.study;
public class Test {
public static void main(String[] args) {
System.out.println("i love study");
}
}
3.创建一个service,一个impl
package com.study;
public interface StudyService {
String study(String name);
}
package com.study.impl;
import com.study.StudyService;
public class StudyServiceImpl implements StudyService {
@Override
public String study(String name) {
System.out.println(name+"love study");
return "success";
}
}
4.创建一个spring管理的xml文件,创建目录【resource->spring->spring-config.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">
<bean id="studyService" class="com.study.impl.StudyServiceImpl"></bean>
</beans>
5.因为我们要解析xml,并生成spring容器并返回给我们,所以我们需要引用spring 包
//打开build.gradle
plugins {
id 'java'
}
group 'org.springframework'
version '5.2.0.RELEASE'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
compile(project(":spring-context"))
testCompile group: 'junit', name: 'junit', version: '4.12'
}
为什么要引入spring-context包呢,我们可以看下它的引入方法
我们可以看到,它已经引入了spring-core,spring-beans,spring-aop等赖以生存的模块,所以我们只需要引入它就可以了 。
6.在Test类里解析xml,获取spring bean对象
package com.study;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
public class Test {
public static void main(String[] args) {
System.out.println("i love study");
String xmlPath = "E:\\study\\spring\\spring-framework-5.2.0.RELEASE\\spring-demo\\src\\main\\resources\\spring\\spring-config.xml";
ApplicationContext applicationContext = new FileSystemXmlApplicationContext(xmlPath);
StudyService studyService = (StudyService)applicationContext.getBean("studyService");
studyService.study("lishengjie");
}
}
引用成功。