什么是Spring框架
1、概述
是一个轻量级的企业级应用框架
企业应用开发的"一站式"选择,贯穿于表现层、业务层、持久层
1.1、优点
1、 低侵入式设计
2、独立于各种应用服务器
3、依赖注入特性将组件关系透明化,降低耦合度
4、面向切面编程特性允许将通用任务进行集中式处理
5、与第三方框架的良好整合
1.2、Spring体系结构
1.3、Spring设计理念
1.4、Spring两大核心技术
1、控制反转(IoC:Inversion of Control)/依赖注入(DI:Dependency Injection)
创建对象的控制权转移,是一种程序设计思想
2、面向切面编程(AOP:Aspect Oriented Programming)
将依赖的对象注入到需要的类中去,是"控制反转"设计思想的具体实现方式
2、创建Spring项目
1.前期准备
分别创建Dao层的Service层接口和实现类:
Dao层接口代码如下:
Dao层代码实现如下:
Service层接口如下:
Service层实现类如下:
2.导入坐标
使用Maven工具管理项目,我们需要导入Spring对应的Maven坐标
Spring坐标导入:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.2.RELEASE</version>
</dependency>
3.编写配置文件
applicationContext.xml
的头部文件主要包含以下内容:
1、XML声明:头部文件应以XML声明开始,指定XML版本和字符编码。例如:
<?xml version="1.0" encoding="UTF-8"?>
2、命名空间的引入:为了使用Spring框架提供的各种特性和标签,需要引入相应的命名空间。通常会引入xmlns
前缀为beans
的命名空间,它是Spring核心模块的命名空间。例如:
xmlns:beans="http://www.springframework.org/schema/beans"
3、模式约束的引入:为了验证和验证XML配置的正确性,需要引入相应的模式约束。通常会引入xsi:schemaLocation
属性来指定使用的模式约束文件。例如:
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd"
综上所述,applicationContext.xml
的典型头部文件如下所示:
<?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">
</beans>
4.测试类编写
测试代码:
测试结果:
3、面向切面编程(AOP)
3、AOP相关术语
4、表达式匹配规则举例
public * addNewUser(entity.User):"*"表示匹配所有类型的返回值
public void *(entity.User):"*"表示匹配所有方法名
public void addNewUser(..):".."表示匹配任意参数个数和类型
* com.service.*.*(..):匹配com.service包下所有类的所有方法
* com.service..*.*(..):匹配com.service包及其子包下所有类的所有方法