1 安装环境
《Spring源码阅读1 – Mac使用Idea工具编译Spring5源码(v5.1.6)+测试spring源码》:https://clevercode.blog.csdn.net/article/details/114232589
2 修改build.gradle
dependencies {
compile project(":spring-context")
testCompile group: 'junit', name: 'junit', version: '4.12'
}
3 添加类文件
1、OrderService
package com.clevercode;
public class OrderService {
private int id;
OrderService(){
System.out.println("OrderService construct");
}
public void setId(int id){
this.id = id;
}
public int getId(){
return this.id;
}
}
2、UserService
package com.clevercode;
public class UserService {
private String name;
UserService(){
System.out.println("UserService construct");
}
public void setName(String name){
this.name = name;
}
public String getName(){
return this.name;
}
}
4 xml文件
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="orderService" class="com.clevercode.OrderService"/>
<bean id="userService" class="com.clevercode.UserService"/>
</beans>
5 测试
新建测试类
package com.clevercode;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
//初始化spring容器
ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("spring-config.xml");
//通过class 获取bean
OrderService orderService = ac.getBean(OrderService.class);
orderService.setId(10);
System.out.println(orderService.getId());
//通过name获取bean
UserService userService = (UserService) ac.getBean("userService");
userService.setName("CleverCode");
System.out.println(userService.getName());
}
}
6 测试
ClassPathXmlApplicationContext 类图
技术交流
欢迎关注我的微信公众号:程序员大宝。一个乐于分享的程序员!关注免费领取架构师学习资料和精选大厂高频面试题库。