Spring 容器
两个核心接口:BeanFactory 和 ApplicationContext(是BeanFactory的子接口),生成Bean实例并管理Bean的工厂
Bean 对象
Spring管理的基本单位,在基于Spring应用中,所有的组件都可以理解为是一个 Bean 对象
启动 Spring 容器
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="demo1Service" class="com.example.demo.demo1.Demo1ServiceImpl"/>
<bean id="demo1Service2" class="com.example.demo.demo1.Demo1ServiceImpl2"/>
</beans>
FileSystemXmlApplicationContext
//在当前路径下加载配置文件
ApplicationContext context = newFileSystemXmlApplicationContext("demo1.xml");
//在当前路径下加载 demo1.xml、demo2.xml、demo3.xml 配置文件
String[] locations = {"demo1.xml", "demo1.xml", "demo1.xml"};
ApplicationContext context = new FileSystemXmlApplicationContext(locations );
//在classpath路径下加载配置文件
ApplicationContext context = new FileSystemXmlApplicationContext("classpath:demo1.xml");
//在 D:/project/demo1.xml 下配置文件
ApplicationContext context = new FileSystemXmlApplicationContext("D:/project/demo1.xml");
ClassPathXmlApplicationContext
//默认在 ClassPath 中寻找 xml 配置文件,根据 xml 文件内容来构建 ApplicationContext
ApplicationContext context = new ClassPathXmlApplicationContext("demo1.xml");
//在 绝对路径 中寻找 xml 配置文件,根据 xml 文件内容来构建 ApplicationContext
ApplicationContext context = new ClassPathXmlApplicationContext("file:D:/project/demo1.xml");
AnnotationConfigApplicationContext
实现了Bean定义的注册、Bean的实例化、事件、生命周期、国际化等功能
获取 Spring 容器中的 Bean
Demo1Service demo1Service = context.getBean("demo1Service", Demo1Service.class);
demo1Service.demo1();
Demo1Service demo1Service2 = context.getBean("demo1Service2", Demo1Service.class);
demo1Service2.demo1();