Spring-Ioc
- IoC(Inversion of Control)控制反转,Spring反向控制应用程序所需要的外部资源
- Spring 控制的资源全部放置在Spring容器中,这个容器称为IoC容器
Spring入门
- Spring的Maven坐标
<dependency>
<groupId>org.springframework</groupid>
<artifactId>spring-context</artifactId>
</dependency>
- Spring的配置文件
在spring.io官网中查看springframework文档的core有配置文件
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd">
</beans>
- Spring控制的资源
<!-- bean可以有多个名称,可以用name数学标注多个名称-->
<bean id = "" class = "com.XX.XXX.XX"></bean>
- 加载Spring配置文件
#加载配置文件
ApplicationContext ctx = new ClassPathXmlApplicationContext("ApplicationContext.xml");
#获取资源
UserService userService = (UserService)ctx.getBean("userService");
#执行资源方法
userService.save();
IoC配置
-
bean
- 作用:定义Spring中的资源,受spring控制
- name属性:bean的名称,可以通过name获取bean
- scope属性:定义bean的作用范围
- 取值:
singleton:单例对象-单例模式在加载spring配置文件时,就运行方法。
prototype:非单例对象
request、session、application、websocket
- 取值:
- bean的生命周期属性:init-method、destroy-method
- 作用:定义bean对象在生成和销毁时需要完成的任务
- 取值:bean对应类中的具体方法名
- 注意事项:scope为非单例模式时,destroy方法不会执行,对象的销毁由垃圾回收机制控制。
-
DI-依赖注入
DI 依赖注入,应用程序运行依赖的资源由spring为其提供,资源进入应用程序的方式称为注入。
- set注入(主流方式)
- 标签:property
- 读取properties文件
- 加载命名空间的支持
xmlns:context="http://www.springframework.org/schme/context"
xsi:schemaLocation=“
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
"
- 加载配置文件
<context:property-placeholder location="classpath:*.properties"
3.读取配置文件内容
value="${配置文件中的变量名}"