一、spring项目环境搭建
1.1、项目创建
1.1.1、在eclipse中新建一个maven project
1.1.2、在pom.xml中加入启动spring环境的最基本的依赖
本次源码解析以5.0.7.RELEASE代码为准,不保证其他版本spring代码与之一致。
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.7.RELEASE</version>
</dependency>
1.2、编写测试代码
1)配置类
package study.spring.application;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan("study.spring")
public class AppConfig {
}
2)测试用的service类
package study.spring.application.service;
import org.springframework.stereotype.Service;
@Service
public class UserService {
public void addUser() {
System.out.println("add User...");
}
}
3)spring容器启动类
package study.spring.application;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import study.spring.application.service.UserService;
public class Lanuch {
public static void main(String[] args) {
AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(AppConfig.class);
UserService userService = ac.getBean(UserService.class);
userService.addUser();
}
}
1.3、运行结果
运行启动类的main方法,会看到控制台打印:
三月 07, 2020 12:24:29 下午 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@45ff54e6: startup date [Sat Mar 07 12:24:29 CST 2020]; root of context hierarchy
add User...
说明容器启动成功,并将UserService放入到了容器中管理
1.4、知识点
1.4.1、AnnotationConfigApplicationContext是ApplicationContext的子类。
类继承图如下:
AnnotationConfigApplicationContext是以注解配置方式启动的非web应用spring容器类。
AnnotationConfigWebApplicationContext是以注解配置方式启动的web应用spring容器类。
AnnotationConfigServletWebServerApplicationContext是spring boot应用的spring容器类。
1.4.2、ApplicationContext和BeanFactory的关系和区别
ApplicationContext和BeanFactory都是用来spring容器类。从类继承结构图,我们可以看出ApplicationContext接口是BeanFactory的子接口,所以ApplicationContext包含了BeanFactory的所有功能,同时ApplicationContext类扩展了更多的功能。例如:国际化的支持、spring消息管理、AOP等。