羊蹓狼 发表于 2023-4-7 23:25:36

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

前言

讲解Spring之前,我们首先梳理下Spring有哪些知识点可以进行入手源码分析,比如:

[*]Spring IOC依赖注入
[*]Spring AOP切面编程
[*]Spring Bean的声明周期底层原理
[*]Spring 初始化底层原理
[*]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中的内容为:
如果对上面的代码或者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类 解析配置类,那么调用该构造方法除开会实例化得到一个对象,还会做哪些事情?
[*]从context中获取一个名字为"userService"的userService对象,那么为什么输入一个字符串就可以得到对象呢,好像跟Map有些类似,getBean()又是如何实现的?返回的UserService对象和我们自己直接new的UserService对象有区别吗?
[*]通过获取到的UserService对象调用test方法,这个不难理解。
虽然我们目前很少直接使用这种方式来使用Spring,而是使用Spring MVC或者Spring Boot,但是它们都是基于上面这种方式的,都需要在内部去创建一个
ApplicationContext的,只不过:

[*]Spring MVC创建的是XmlWebApplicationContext,和ClassPathXmlApplicationContext类似,都是基于XML配置的
[*]Spring Boot创建的是AnnotationConfigApplicationContext
根据上面这三步我们大概找到了进行源码深入的方向,本章只是简单讲解下如何简单使用Spring,先对这些流程有个印象,并带着疑惑来进一步探究Spring的内部机制,好了,今天就讲到这里,我是小雨,我们下期再见。
https://img2023.cnblogs.com/blog/1423484/202304/1423484-20230407221737290-864478694.png

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
页: [1]
查看完整版本: Spring源码系列一:入门——Hello World