Spring源码学习,Spring Framework源码编译

98 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第32天,点击查看活动详情

🍀Spring Framework源码编译

博主本地java版本为 java version "11.0.10"

🍀拉取源码

选定存放路径直接只用git clone拉取最新源码

git clone https://github.com/spring-projects/spring-framework.git

目前最新RELEASE版本是5.2.18,编译前需要将tag切换至这个版本。 在这里插入图片描述

git checkout a1225f0

在这里插入图片描述

🍀修改仓库镜像地址,加快依赖下载速度

vim  build.gradle

进入后直接输入/repositories,搜索仓库镜像设置。 在这里插入图片描述 加下来添加阿里云的镜像地址。 回车后,按i进入编辑模式,输入以下代码。

// 阿里云
maven {url "https://maven.aliyun.com/nexus/content/groups/public/"} 
maven {url "https://maven.aliyun.com/nexus/content/repositories/jcenter"}
​

在这里插入图片描述ESC后,输入:wq保存并退出。

🍀源码命令行编译测试

使用以下两条指令进行编译测试

./gradlew :spring-oxm:compileTestJava // 官方建议
./gradlew :spring-core:compileTestJava

在这里插入图片描述 在这里插入图片描述

🍀导入IDEA

idea版本 在这里插入图片描述 导入IDEA后会自动编译,会自动重新下载依赖。

☘️创建一个新的Module

在这里插入图片描述 在这里插入图片描述 在这里插入图片描述 创建Module成功。

☘️给Module加依赖

compile(project(":spring-context"))

在这里插入图片描述 添加依赖后,需要重新加载。

🍀使用ApplicationContext获取自定义的Bean

在这里插入图片描述

package com.ber.service;
​
/**
 * @author ber
 * @version 1.0
 * @date 21/11/9 13:12
 */
public interface MsgService {
  String getMsg();
}
​
package com.ber.service.impl;
​
import com.ber.service.MsgService;
import org.springframework.stereotype.Service;
​
/**
 * @author ber
 * @version 1.0
 * @date 21/11/9 13:13
 */
@Service("msg")
public class MsgServiceImpl implements MsgService {
  @Override
  public String getMsg() {
    return "Hello Ber!";
  }
}
​
package com.ber;
​
import com.ber.service.MsgService;
import com.ber.service.impl.MsgServiceImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
​
import java.util.Arrays;
​
/**
 * @author ber
 * @version 1.0
 * @date 21/11/9 13:18
 */
@ComponentScan({"com.ber"})
public class Application {
  public static void main(String[] args) {
    ApplicationContext context = new AnnotationConfigApplicationContext(Application.class);
    MsgService msgService = (MsgServiceImpl) context.getBean("msg");
    System.out.println(msgService.getMsg());
    System.out.println(context.getBeanDefinitionCount());
    Arrays.stream(context.getBeanDefinitionNames()).forEach(System.out::println);
​
    Application application = (Application) context.getBean("application");
    System.out.println(application.getMsg());
  }
​
  public String getMsg() {
    return "Hello Ber!!!";
  }
}
​

@Service注解是在spring-context中,前面依赖导入的作用就体现了。指定msgcomponent name

@ComponentScan注解也是在spring-context中,这里指定扫描包com.ber下的component names

在程序中通过AnnotationConfigApplicationContext来获取由Spring自动创建的msgapplication这两个Bean,并且调用其方法。 在这里插入图片描述

☘️运行测试

在这里插入图片描述 这里可以看出一共有6个Bean,我们定义了2个Bean,分别是msgapplication。通过AnnotationConfigApplicationContext获取Bean也成功获取到了其中的方法。

🍀参考

spring.io/projects/sp…