Spring源码阅读3 -- Spring5.1.6源码AnnotationConfigApplicationContext方式测试bean

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 类图

在这里插入图片描述

技术交流

欢迎关注我的微信公众号:程序员大宝。一个乐于分享的程序员!关注免费领取架构师学习资料和精选大厂高频面试题库。
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值