1. spring概述
1.1 框架概述(理解)
框架是一个封装了很多功能和模块的程序的半成品。
可以理解为是一个由很多工具类组合而成的一个工具包。
1.2 Spring是什么(理解)
Spring是分层的 Java SE/EE应用 full-stack 轻量级开源框架。是Java开发的灵魂框架。
Spring有两大内核:
IOC(Inverse Of Control:控制反转)
AOP(Aspect Oriented Programming:面向切面编程)
1.3 Spring功能
**IOC:**控制反转,其实就是把对象的创建权,交给spring,由Spring负责给我们创建对象
DI: 依赖注入,其实就是给对象的成员变量赋值。
**AOP:**面向切面编程,底层就是动态代理
事务: Spring提供了声明式事务,也就是说,我们可以通过配置的方式来添加事务。
2 入门案例
2.1 Spring程序开发步骤
①导入 Spring 开发的基本包坐标(5.1.9.release)
②编写业务层与表现层
③创建Spring核心配置文件
④在 Spring 配置文件中配置要创建的对象
⑤通过spring获取资源(获取创建的对象)
先来看一下项目结构:
①导入 Spring 开发的基本包坐标(5.1.9.release)
<--Spring核心配置文件-->
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
</dependencies>
②编写业务层与表现层
//定义一个Service层
public interface UserService {
public void show();
}
//实现类
public class UserServiceImpl implements UserService {
public void show() {
System.out.println("Uservice is running....");
}
}
③创建Spring核心配置文件 applicationContext.xml
④在 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">
<!-- 1.创建spring控制的资源(让spring帮忙创建该类的对象)-->
<!--相当于: UserService userService= new UserServiceImpl();-->
<bean id="userService" class="com.itheima.service.impl.UserServiceImpl"/>
</beans>
⑤通过spring获取资源(获取创建的对象)
import com.itheima.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class UserApp {
public static void main(String[] args) {
//2.加载配置文件
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
//3.获取资源(这里的ctx.getBean("userService"); 参数对应applicationContext.xml 文件中<bean>标签的id)
UserService userService = (UserService) ctx.getBean("userService");
userService.show();
}
}
3 IOC配置-XML格式
3.1 Bean标签基本配置
作用:定义spring中的资源,受此标签定义的资源将受到spring控制
格式:
<beans>
<bean 属性名="属性值" ></bean>
</beans>
3.2 常见属性
属性名 | 说明 |
---|---|
id | Bean实例在Spring容器中的唯一标识,通过id值获取bean |
class | Bean的类型, spring创建的就是该类的对象 |
name | Bean的名称,可以通过name值获取bean,用于多人配合时给bean起别名 |
3.3 其他属性
3.3.1 scope
-
作用:定义bean的作用范围
-
格式:
<bean scope="singleton"></bean>
-
取值:
- singleton:设定创建出的对象保存在spring容器中,是一个单例的对象,
- prototype:设定创建出的对象保存在spring容器中,是一个非单例的对象
- request、session、application、 websocket :设定创建出的对象放置在web容器对应的位置
3.3.2 生命周期(了解)
-
名称:init-method,destroy-method
-
作用:定义bean对象在初始化或销毁时完成的工作
-
格式:
<bean init-method="bean初始化时执行的方法" destroy-method="bean销毁时执行的方法"></bean>
-
注意事项:
- 当scope=“singleton”时,spring容器中有且仅有一个对象,init方法在创建容器时仅执行一次
- 当scope=“prototype”时,spring容器要创建同一类型的多个对象,init方法在每个对象创建时均执行一次
- 当scope=“singleton”时,关闭容器会导致bean实例的销毁,调用destroy方法一次
- 当scope=“prototype”时,对象的销毁由垃圾回收机制gc()控制,destroy方法将不会被执行