1 安装环境
《Spring源码阅读1 – Mac使用Idea工具编译Spring5源码(v5.1.6)+测试spring源码》:https://clevercode.blog.youkuaiyun.com/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;
@Component
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;
@Component
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 AppConfig
@ComponentScan(“com.clevercode”) 扫描 com.clevercode包下面的类。
package com.clevercode;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan("com.clevercode")
public class AppConfig {
}
5 测试
新建测试类
package com.clevercode;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Test {
public static void main(String[] args) {
//初始化spring容器
AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(AppConfig.class);
//通过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 测试
7 AnnotationConfigApplicationContext 类图
技术交流
欢迎关注我的微信公众号:程序员大宝。一个乐于分享的程序员!关注免费领取架构师学习资料和精选大厂高频面试题库。