Spring源码系列一:入门——Hello World

科技资讯 投稿 6200 0 评论

Spring源码系列一:入门——Hello World

前言

    Spring IOC依赖注入
  1. Spring AOP切面编程
  2. Spring Bean的声明周期底层原理
  3. Spring 初始化底层原理
  4. Spring Transaction事务底层原理

Hello World

通过这些知识点,后续我们慢慢在深入Spring的使用及原理剖析,为了更好地理解Spring,我们需要先了解一个最简单的示例——Hello World。在学习任何框架和语言之前,Hello World都是必不可少的。

//在以前大家都是spring.xml进行注入bean后供Spring框架解析
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring.xml";
UserService userService = (UserService context.getBean("userService";
userService.test(;

spring.xml中的内容为:

<context:component-scan base-package="com.zhouyu"/>
<bean id="userService" class="com.zhouyu.service.UserService"/>

如果对上面的代码或者xml形式很陌生,再看下面一种代码,也是目前流行的一种形式

//通过我们的配置类进行注入bean并解析
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MySpringConfig.class;
//ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring.xml";
UserService userService = (UserService context.getBean("userService";
userService.test(

MySpringConfig中的内容为:

@ComponentScan("com.xiaoyu"
public class MySpringConfig {
	@Bean
	public UserService userService({
		return new UserService(;
	}
}

相信很多人都会对上面的代码不陌生,那我们来看下这三行代码都做了那些工作:

    构造一个ClassPathXmlApplicationContext类解析配置文件 或者AnnotationConfigApplicationContext类 解析配置类,那么调用该构造方法除开会实例化得到一个对象,还会做哪些事情?
  1. 从context中获取一个名字为"userService"的userService对象,那么为什么输入一个字符串就可以得到对象呢,好像跟Map<String,Object>有些类似,getBean(又是如何实现的?返回的UserService对象和我们自己直接new的UserService对象有区别吗?
  2. 通过获取到的UserService对象调用test方法,这个不难理解。

ApplicationContext的,只不过:

    Spring MVC创建的是XmlWebApplicationContext,和ClassPathXmlApplicationContext类似,都是基于XML配置的
  1. Spring Boot创建的是AnnotationConfigApplicationContext

编程笔记 » Spring源码系列一:入门——Hello World

赞同 (28) or 分享 (0)
游客 发表我的评论   换个身份
取消评论

表情
(0)个小伙伴在吐槽