注:本笔记是本人根据尚硅谷spring6学习视频实操,并使用了尚硅谷提供的笔记结合编写。以供本人及读者复习回顾使用,再次感谢尚硅谷的免费学习视频!
学习视频:【尚硅谷Spring零基础入门到进阶,一套搞定spring6全套视频教程(源码级讲解)】 https://www.bilibili.com/video/BV1kR4y1b7Qc/?share_source=copy_web&vd_source=4d877b7310d01a59f27364f1080e3382
1、 概述
1.1、Spring是什么?
广义的 Spring:Spring 技术栈
广义上的 Spring 泛指以 Spring Framework 为核心的 Spring 技术栈。
经过十多年的发展,Spring 已经不再是一个单纯的应用框架,而是逐渐发展成为一个由多个不同子项目(模块)组成的成熟技术,例如 Spring Framework、Spring MVC、SpringBoot、Spring Cloud、Spring Data、Spring Security 等,其中 Spring Framework 是其他子项目的基础。
这些子项目涵盖了从企业级应用开发到云计算等各方面的内容,能够帮助开发人员解决软件发展过程中不断产生的各种实际问题,给开发人员带来了更好的开发体验。
狭义的 Spring:Spring Framework
狭义的 Spring 特指 Spring Framework,通常我们将它称为 Spring 框架。
Spring 框架是一个分层的、面向切面的 Java 应用程序的一站式轻量级解决方案,它是 Spring 技术栈的核心和基础,是为了解决企业级应用开发的复杂性而创建的。
1.2、Spring Framework特点
- 非侵入式:使用 Spring Framework 开发应用程序时,Spring 对应用程序本身的结构影响非常小。对领域模型可以做到零污染;对功能性组件也只需要使用几个简单的注解进行标记,完全不会破坏原有结构,反而能将组件结构进一步简化。这就使得基于 Spring Framework 开发应用程序时结构清晰、简洁优雅。
- 控制反转:IoC——Inversion of Control,翻转资源获取方向。把自己创建资源、向环境索取资源变成环境将资源准备好,我们享受资源注入。
- 面向切面编程:AOP——Aspect Oriented Programming,在不修改源代码的基础上增强代码功能。
- 容器:Spring IoC 是一个容器,因为它包含并且管理组件对象的生命周期。组件享受到了容器化的管理,替程序员屏蔽了组件创建过程中的大量细节,极大的降低了使用门槛,大幅度提高了开发效率。
- 组件化:Spring 实现了使用简单的组件配置组合成一个复杂的应用。在 Spring 中可以使用 XML 和 Java 注解组合这些对象。这使得我们可以基于一个个功能明确、边界清晰的组件有条不紊的搭建超大型复杂应用系统。
- 一站式:在 IoC 和 AOP 的基础上可以整合各种企业应用的开源框架和优秀的第三方类库。而且 Spring 旗下的项目已经覆盖了广泛领域,很多方面的功能性需求可以在 Spring Framework 的基础上全部使用 Spring 来实现。
1.3、Spring模块组成
(1)Spring Core(核心容器)
spring core提供了IOC,DI,Bean配置装载创建的核心实现。核心概念: Beans、BeanFactory、BeanDefinitions、ApplicationContext。
- spring-core :IOC和DI的基本实现
- spring-beans:BeanFactory和Bean的装配管理(BeanFactory)
- spring-context:Spring context上下文,即IOC容器(AppliactionContext)
- spring-expression:spring表达式语言
(2)Spring AOP - spring-aop:面向切面编程的应用模块,整合ASM,CGLib,JDK Proxy
- spring-aspects:集成AspectJ,AOP应用框架
- spring-instrument:动态Class Loading模块
(3)Spring Data Access - spring-jdbc:spring对JDBC的封装,用于简化jdbc操作
- spring-orm:java对象与数据库数据的映射框架
- spring-oxm:对象与xml文件的映射框架
- spring-jms: Spring对Java Message Service(java消息服务)的封装,用于服务之间相互通信
- spring-tx:spring jdbc事务管理
(4)Spring Web - spring-web:最基础的web支持,建立于spring-context之上,通过servlet或listener来初始化IOC容器
- spring-webmvc:实现web mvc
- spring-websocket:与前端的全双工通信协议
- spring-webflux:Spring 5.0提供的,用于取代传统java servlet,非阻塞式Reactive Web框架,异步,非阻塞,事件驱动的服务
(5)Spring Message - Spring-messaging:spring 4.0提供的,为Spring集成一些基础的报文传送服务
(6)Spring test - spring-test:集成测试支持,主要是对junit的封装
2、容器:IoC
IoC 是 Inversion of Control 的简写,译为“控制反转”,它不是一门技术,而是一种设计思想,是一个重要的面向对象编程法则,能够指导我们如何设计出松耦合、更优良的程序。
Spring 通过 IoC 容器来管理所有 Java 对象的实例化和初始化,控制对象与对象之间的依赖关系。我们将由 IoC 容器管理的 Java 对象称为 Spring Bean,它与使用关键字 new 创建的 Java 对象没有任何区别。
IoC 容器是 Spring 框架中最重要的核心组件之一,它贯穿了 Spring 从诞生到成长的整个过程。
2.1、IoC容器
2.1.1、控制反转(IoC)
控制反转是一种思想。控制反转是为了降低程序耦合度,提高程序扩展力。
控制反转中的反转:(1)将对象的创建权利交出去,交给第三方容器负责。(2)将对象和对象之间关系的维护权交出去,交给第三方容器负责。
控制反转思想通过DI(Dependency Injection)依赖注入实现。
2.1.2、 依赖注入
DI(Dependency Injection):依赖注入,依赖注入实现了控制反转的思想。指Spring创建对象的过程中,将对象依赖属性通过配置进行注入。依赖注入常见的实现方式包括两种:(1)set注入。(2)依赖注入。
2.1.3、IoC容器在Spring的实现
Spring 的 IoC 容器就是 IoC思想的一个落地的产品实现。IoC容器中管理的组件也叫做 bean。在创建 bean 之前,首先需要创建IoC 容器。Spring 提供了IoC 容器的两种实现方式:
(1)BeanFactory
这是 IoC 容器的基本实现,是 Spring 内部使用的接口。面向 Spring 本身,不提供给开发人员使用。
(2)ApplicationContext
BeanFactory 的子接口,提供了更多高级特性。面向 Spring 的使用者,几乎所有场合都使用 ApplicationContext 而不是底层的 BeanFactory。
ApplicationContext的主要实现类
- ClassPathXmlApplicationContext:通过读取类路径下的 XML 格式的配置文件创建 IOC 容器对象
- FileSystemXmlApplicationContext:通过文件系统路径读取 XML 格式的配置文件创建 IOC 容器对象
- ConfigurableApplicationContext:ApplicationContext 的子接口,包含一些扩展方法 refresh() 和 close() ,让 ApplicationContext 具有启动、关闭和刷新上下文的能力。
- WebApplicationContext:专门为 Web 应用准备,基于 Web 环境创建 IOC 容器对象,并将对象引入存入 ServletContext 域中。
2.2、 基于XML管理Bean
2.2.1、获取bean
(1)方式一:根据id获取
由于 id 属性指定了 bean 的唯一标识,所以根据 bean 标签的 id 属性可以精确获取到一个组件对象。
(2)方式二:根据类型获取
@Test
public void testHelloWorld1(){
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
User bean = context.getBean(User.class);
bean.sayHello();
}
(3)方式三:根据id和类型
@Test
public void testHelloWorld2(){
ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
HelloWorld bean = ac.getBean("helloworld", HelloWorld.class);
bean.sayHello();
}
注意:当根据类型获取bean时,要求IOC容器中指定类型的bean有且只能有一个。若IOC容易配置了两个相同类,则会报错。
拓展:
与用类型获取bean类似
如果组件类实现了接口,根据接口类型可以获取 bean 吗?
答:可以,前提是bean唯一
如果一个接口有多个实现类,这些实现类都配置了 bean,根据接口类型可以获取 bean 吗?
答:不行,因为bean不唯一
2.2.2、 依赖注入之setter注入
(1)创建一个类,该类有属性,set方法,重写toString方法(用于测试)。
(2)配置xml文件
<bean id="book" class="com.atguigu.spring6.iocxml.di.Book">
#相当于调用底层的set方法进行属性的赋值
<property name="bname" value="前端开发"></property>
<property name="author" value="尚硅谷"></property>
</bean>
(3)创建一个测试类进行测试
public class TestBook {
@Test
public void testSetter() {
ApplicationContext context =
new ClassPathXmlApplicationContext("bean-di.xml");
Book book = context.getBean("book", Book.class);
System.out.println(book);
}
}
运行结果:
2.2.3、依赖注入之构造器注入
与上述同理 配置xml文件
<bean id="bookCon" class="com.atguigu.spring6.iocxml.di.Book">
<constructor-arg name="bname" value="java开发"></constructor-arg>
<constructor-arg name="author" value="尚硅谷"></constructor-arg>
</bean>
创建一个测试方法进行测试
@Test
public void testCon() {
ApplicationContext context =
new ClassPathXmlApplicationContext("bean-di.xml");
Book book = context.getBean("bookCon", Book.class);
System.out.println(book);
}
结果如下
2.2.4、 特殊值处理
(1)字面量赋值
字面量没有引申含义,就是我们看到的这个数据本身。
<!-- 使用value属性给bean的属性赋值时,Spring会把value属性的值看做字面量 -->
<property name="name" value="张三"/>
(2)null值
value为空时,不能直接赋值。下列即为name=null
<property name="name">
<null />
</property>
(3)特殊符号(XML实体)
<!-- 小于号在XML文档中用来定义标签的开始,不能随便使用 -->
<!-- 解决方案一:使用XML实体来代替 (转义字符)-->
<property name="expression" value="a < b"/>
(4)CDATA节
<property name="expression">
<!-- 解决方案二:使用CDATA节 -->
<!-- CDATA中的C代表Character,是文本、字符的含义,CDATA就表示纯文本数据 -->
<!-- XML解析器看到CDATA节就知道这里是纯文本,就不会当作XML标签或属性来解析 -->
<!-- 所以CDATA节中写什么符号都随意 -->
<value><![CDATA[a < b]]></value>
</property>
2.2.5、 为对象类型属性赋值
例:有两个类公司和员工,公司类内有部门属性,公司类是员工类的一个属性。
(1)引用外部bean
<bean id="dept" class="com.atguigu.spring6.iocxml.ditest.Dept">
<property name="dname" value="安保部"></property>
</bean>
<bean id="emp" class="com.atguigu.spring6.iocxml.ditest.Emp">
<!--普通属性注入-->
<property name="ename" value="lucy"></property>
<property name="age" value="50"></property>
<!-- 对象属性注入-->
<property name="dept" ref="dept"></property>
</bean>
(2)内部bean
<bean id="emp2" class="com.atguigu.spring6.iocxml.ditest.Emp">
<!--普通属性注入-->
<property name="ename" value="mary"></property>
<property name="age" value="20"></property>
<!-- 内部bean注入-->
<property name="dept">
<bean id="dept2" class="com.atguigu.spring6.iocxml.ditest.Dept">
<property name="dname" value="财务部"></property>
</bean>
</property>
</bean>
(3)级联属性赋值
<bean id="dept3" class="com.atguigu.spring6.iocxml.ditest.Dept">
<property name="dname" value="技术研发部"></property>
</bean>
<bean id="emp3" class="com.atguigu.spring6.iocxml.ditest.Emp">
<property name="ename" value="tom"></property>
<property name="age" value="30"></property>
<property name="dept" ref="dept3"></property>
<property name="dept.dname" value="测试部"></property>
</bean>
2.2.6、 为数组类型属性赋值
<!--数组类型属性-->
<bean id="dept" class="com.atguigu.spring6.iocxml.ditest.Dept">
<property name="dname" value="技术部"></property>
</bean>
<bean id="emp" class="com.atguigu.spring6.iocxml.ditest.Emp">
<!--普通属性-->
<property name="ename" value="lucy"></property>
<property name="age" value="20"></property>
<!--对象类型属性-->
<property name="dept" ref="dept"></property>
<!--数组类型属性-->
<property name="loves">
<array>
<value>吃饭</value>
<value>睡觉</value>
</array>
</property>
</bean>
2.2.7、 为集合类型属性赋值
(1)为List集合类型属性赋值
例:一个部门有很多员工,在部门类中添加List集合员工属性
则配置相应的xml文件为
<bean id="empone" class="com.atguigu.spring6.iocxml.ditest.Emp">
<property name="ename" value="lucy"></property>
<property name="age" value="20"></property>
</bean>
<bean id="emptwo" class="com.atguigu.spring6.iocxml.ditest.Emp">
<property name="ename" value="mary"></property>
<property name="age" value="30"></property>
</bean>
<bean id="dept" class="com.atguigu.spring6.iocxml.ditest.Dept">
<property name="dname" value="技术部"></property>
<property name="empList">
<list>
<ref bean="empone"></ref>
<ref bean="emptwo"></ref>
</list>
</property>
</bean>
(2)为Map集合类型属性赋值
例:创建教师类和学生类,一个学生对应多个老师,因此在学生类中加入Map集合的老师属性。
则xml文件应配置为:
<bean id="teacherone" class="com.atguigu.spring6.iocxml.dimap.Teacher">
<property name="tid" value="100"></property>
<property name="tname" value="pink老师"></property>
</bean>
<bean id="teachertwo" class="com.atguigu.spring6.iocxml.dimap.Teacher">
<property name="tid" value="200"></property>
<property name="tname" value="blue老师"></property>
</bean>
<bean id="student" class="com.atguigu.spring6.iocxml.dimap.Student">
<property name="sid" value="2023"></property>
<property name="sname" value="张三"></property>
<!--在学生bean注入Map集合-->
<property name="teacherMap">
<map>
<entry>
<key>
<value>10010</value>
</key>
<ref bean="teacherone"></ref>
</entry>
<entry>
<key>
<value>20010</value>
</key>
<ref bean="teachertwo"></ref>
</entry>
</map>
</property>
</bean>
(3)引用集合类型的bean
例:一个学生类中有Map集合的老师属性,List集合的Lesson属性。
则xml配置如下
需要修改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"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
代码体
<bean id="student" class="com.atguigu.spring6.iocxml.dimap.Student">
<property name="sid" value="2023"></property>
<property name="sname" value="张三"></property>
<!--输入List Map类型属性-->
<property name="lessonList" ref="lessonList"></property>
<property name="teacherMap" ref="teacherMap"></property>
</bean>
<util:list id="lessonList">
<ref bean="lessonone"></ref>
<ref bean="lessontwo"></ref>
</util:list>
<util:map id="teacherMap">
<entry>
<key>
<value>10010</value>
</key>
<ref bean="teacherone"></ref>
</entry>
<entry>
<key>
<value>20010</value>
</key>
<ref bean="teachertwo"></ref>
</entry>
</util:map>
<bean id="lessonone" class="com.atguigu.spring6.iocxml.ditest.Lesson">
<property name="lessonName" value="前端开发"></property>
</bean>
<bean id="lessontwo" class="com.atguigu.spring6.iocxml.ditest.Lesson">
<property name="lessonName" value="后端开发"></property>
</bean>
<bean id="teacherone" class="com.atguigu.spring6.iocxml.dimap.Teacher">
<property name="tid" value="100"></property>
<property name="tname" value="pink老师"></property>
</bean>
<bean id="teachertwo" class="com.atguigu.spring6.iocxml.dimap.Teacher">
<property name="tid" value="200"></property>
<property name="tname" value="blue老师"></property>
</bean>
2.2.8、 p命名空间
引入p命名空间
xmlns:p="http://www.springframework.org/schema/p"
结合上方部分代码进行xml配置
<bean id="stup" class="com.atguigu.spring6.iocxml.dimap.Student"
p:sid="100" p:sname="luck" p:lessonList-ref="lessonList" p:teacherMap-ref="teacherMap">
</bean>
2.2.9、 引入外部属性文件
例:引入以下数据库配置
jdbc.user=root
jdbc.password=root
jdbc.url=jdbc:mysql://localhost:3306/spring?characterEncoding=utf8&useSSL=false
jdbc.driver=com.mysql.cj.jdbc.Driver
则在xml配置
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- 完成数据库信息的注入-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
<property name="driverClassName" value="${jdbc.driver}"></property>
</bean>
2.2.10、 bean的作用域
在Spring中可以通过配置bean标签的scope属性来指定bean的作用域范围
singleton(默认):在IOC容器中,这个bean的对象始终为单实例(只创建一个对象),IOC容器初始化时创建对象。
prototype:这个bean在IOC容器中有多个实例(创建了多个对象),获取bean时创建对象。
例:演示prototype,xml配置如下:
<bean id="orders" class="com.atguigu.spring6.iocxml.scope.Orders"
scope="prototype">
</bean>
测试结果如下,生成了多个实例:
2.2.11、 bean生命周期
(1)具体的生命周期过程
- bean对象创建(调用无参构造器)
- 给bean对象设置属性
- bean的后置处理器(初始化之前)
- bean对象初始化(需在配置bean时指定初始化方法)
- bean的后置处理器(初始化之后)
- bean对象就绪可以使用
- bean对象销毁(需在配置bean时指定销毁方法)
- IOC容器关闭
例:创建一个User类,在无参构造器输出1,在set方法输出2,写一个初始化方法用于提示初始化完成,销毁方法用于提示销毁。
则测试代码为:
public static void main(String[] args) {
ClassPathXmlApplicationContext context =
new ClassPathXmlApplicationContext("bean-life.xml");
User user = context.getBean("user", User.class);
System.out.println("6 bean对象创建完成,可以使用了");
System.out.println(user);
context.close();
}
xml配置为;
<bean id="user" class="com.atguigu.spring6.iocxml.life.User" scope="singleton"
init-method="initMethod" destroy-method="destroyMethod">
<property name="name" value="lucy"></property>
</bean>
<!-- bean的后置处理器要放入IOC容器才能生效 -->
<bean id="myBeanProcessor" class="com.atguigu.spring6.iocxml.life.MyBeanPost"/>
重写BeanPostProcessor类的后置器:
public class MyBeanPost implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName)
throws BeansException {
System.out.println("3 后置处理器,before");
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName)
throws BeansException {
System.out.println("5 后置处理器,after");
return bean;
}
}
输出结果:
2.2.12、 FactoryBean
FactoryBean是Spring提供的一种整合第三方框架的常用机制。和普通的bean不同,配置一个FactoryBean类型的bean,在获取bean的时候得到的并不是class属性中配置的这个类的对象,而是getObject()方法的返回值。通过这种机制,Spring可以帮我们把复杂组件创建的详细过程和繁琐细节都屏蔽起来,只把最简洁的使用界面展示给我们。
xml配置:
<bean id="user" class="com.atguigu.spring6.iocxml.factorybean.MyFactoryBean"></bean>
测试代码:
public static void main(String[] args) {
ApplicationContext context =
new ClassPathXmlApplicationContext("bean-factorybean.xml");
User user = (User)context.getBean("user");
System.out.println(user);
}
结果得到user对象而不是MyFactoryBean对象
###2.2.13、基于xml自动装配
自动装配:根据指定的策略,在IOC容器中匹配某一个bean,自动为指定的bean中所依赖的类类型或接口类型属性赋值。
使用bean标签的autowire属性设置自动装配效果
自动装配方式:byType
byType:根据类型匹配IOC容器中的某个兼容类型的bean,为属性自动赋值
若在IOC中,没有任何一个兼容类型的bean能够为属性赋值,则该属性不装配,即值为默认值null。若在IOC中,有多个兼容类型的bean能够为属性赋值,则抛出异常NoUniqueBeanDefinitionException
<bean id="userController" class="com.atguigu.spring6.iocxml.auto.controller.UserController"
autowire="byType">
</bean>
<bean id="userService" class="com.atguigu.spring6.iocxml.auto.service.UserServiceImpl"
autowire="byType">
</bean>
<bean id="userDao" class="com.atguigu.spring6.iocxml.auto.dao.UserDaoImpl">
</bean>
自动装配方式:byName
byName:将自动装配的属性的属性名(id需要与属性名保持一致),作为bean的id在IOC容器中匹配相对应的bean进行赋值。
<bean id="userController" class="com.atguigu.spring6.iocxml.auto.controller.UserController"
autowire="byName">
</bean>
<bean id="userService" class="com.atguigu.spring6.iocxml.auto.service.UserServiceImpl"
autowire="byName">
</bean>
<bean id="userDao" class="com.atguigu.spring6.iocxml.auto.dao.UserDaoImpl">
</bean>
2.3、基于注解管理Bean
2.3.1、 开启组件扫描
Spring 默认不使用注解装配 Bean,因此我们需要在 Spring 的 XML 配置中,通过 context:component-scan 元素开启 Spring Beans的自动扫描功能。开启此功能后,Spring 会自动从扫描指定的包(base-package 属性设置)及其子包下的所有类,如果类上使用了 @Component 注解,就将该类装配到容器中。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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--开启组件扫描功能-->
<context:component-scan base-package="com.atguigu.spring6"></context:component-scan>
</beans>
注意:在使用 context:component-scan 元素开启自动扫描功能前,首先需要在 XML 配置的一级标签 中添加 context 相关的约束。
- 最基本的扫描方式
<context:component-scan base-package="com.atguigu.spring6">
</context:component-scan>
- 指定要排除的组件
<context:component-scan base-package="com.atguigu.spring6">
<!-- context:exclude-filter标签:指定排除规则 -->
<!--
type:设置排除或包含的依据
type="annotation",根据注解排除,expression中设置要排除的注解的全类名
type="assignable",根据类型排除,expression中设置要排除的类型的全类名
-->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
<!--<context:exclude-filter type="assignable" expression="com.atguigu.spring6.controller.UserController"/>-->
</context:component-scan>
- 仅扫描指定组件
<context:component-scan base-package="com.atguigu" use-default-filters="false">
<!-- context:include-filter标签:指定在原有扫描规则的基础上追加的规则 -->
<!-- use-default-filters属性:取值false表示关闭默认扫描规则 -->
<!-- 此时必须设置use-default-filters="false",因为默认规则即扫描指定包下所有类 -->
<!--
type:设置排除或包含的依据
type="annotation",根据注解排除,expression中设置要排除的注解的全类名
type="assignable",根据类型排除,expression中设置要排除的类型的全类名
-->
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
<!--<context:include-filter type="assignable" expression="com.atguigu.spring6.controller.UserController"/>-->
</context:component-scan>
2.3.2、 使用注解定义 Bean
Spring 提供了以下多个注解,这些注解可以直接标注在 Java 类上,将它们定义成 Spring Bean。
- @Component:该注解用于描述 Spring 中的 Bean,它是一个泛化的概念,仅仅表示容器中的一个组件(Bean),并且可以作用在应用的任何层次,例如 Service 层、Dao 层等。 使用时只需将该注解标注在相应类上即可。
- @Repository:该注解用于将数据访问层(Dao 层)的类标识为 Spring 中的 Bean,其功能与 @Component 相同。
- @Service:该注解通常作用在业务层(Service 层),用于将业务层的类标识为 Spring 中的 Bean,其功能与 @Component 相同。
- @Controller:该注解通常作用在控制层(如SpringMVC 的 Controller),用于将控制层的类标识为 Spring 中的 Bean,其功能与 @Component 相同。
2.3.3、 @Autowired注入
单独使用@Autowired注解,默认根据类型装配。【默认是byType】
- 属性注入
创建UserDao接口
public interface UserDao {
public void add();
}
创建UserDaoImpl实现
public class UserDaoImpl implements UserDao{
@Override
public void add() {
System.out.println("dao执行。。。");
}
}
创建UserService接口
public interface UserService {
public void add();
}
创建UserServiceImpl实现类
public class UserServiceImpl implements UserService{
//注入Dao
//第一种方式 属性注入
@Autowired //根据类型找到对应对象,完成注入
private UserDao userDao;
@Override
public void add() {
System.out.println("service执行。。。");
userDao.add();
}
}
创建UserController类
public class UserController {
//注入service
//第一种注入方式 属性注入
@Autowired //根据类型找到对应对象,完成注入
private UserService userService;
public void add(){
System.out.println("controller执行。。。");
userService.add();
}
}
测试代码:
public static void main(String[] args) {
ApplicationContext context =
new ClassPathXmlApplicationContext("bean.xml");
UserController controller = context.getBean(UserController.class);
controller.add();
}
结果:
以上构造方法和setter方法都没有提供,经过测试,仍然可以注入成功。
- set注入
即创建set方法,并在set方法上加注解@Autowired
同上,UserController类增加set方法:
@Autowired
public void setUserService(UserService userService) {
this.userService = userService;
}
UserServiceImpl类增加set方法:
@Autowired
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
其他代码均不做变化,运行结果为:
- 构造方法注入
同上,去除set方法后,加入构造器,并在构造器上添加注解@Autowired
UserController类增加构造器:
@Autowired
public UserController(UserService userService) {
this.userService = userService;
}
UserServiceImpl类增加构造器:
@Autowired
public UserServiceImpl(UserDao userDao) {
this.userDao = userDao;
}
其余均不做改变,测试结果:
- 形参上注入
UserController类构造器的形参上加注解:
public UserController(@Autowired UserService userService) {
this.userService = userService;
}
UserServiceImpl类构造器的形参上加注解:
public UserServiceImpl(@Autowired UserDao userDao) {
this.userDao = userDao;
}
- 只有一个构造函数,无注解
UserController类构造器不加注解:
public UserController(UserService userService) {
this.userService = userService;
}
UserServiceImpl类构造器不加注解:
public UserServiceImpl(UserDao userDao) {
this.userDao = userDao;
}
运行结果:
当有参数的构造方法只有一个时,@Autowired注解可以省略。多个的话,则会报错。
- @Autowired注解和@Qualifier注解联合
当一个接口有多个实现类时,那么就不可以用类型装配,需要根据名称进行装备。创建了一个UserRedisDaoImpl类用于实现UserDao接口,那么它就有两个实现类了。
UserRedisDaoImpl类:
@Repository
public class UserRedisDaoImpl implements UserDao{
@Override
public void add() {
System.out.println("dao redis 输出。。。");
}
}
则,UserServiceImpl类变更为(value值默认为类的首字母小写形式):
@Autowired
@Qualifier(value = "userRedisDaoImpl")
private UserDao userDao;
则测试结果:
2.3.4、 @Resource注入
@Resource注解和@Autowired注解的区别?
(1)@Resource注解是JDK扩展包中的,也就是说属于JDK的一部分。所以该注解是标准注解,更加具有通用性。@Autowired注解是Spring框架自己的。
(2)@Resource注解默认根据名称装配byName,未指定name时,使用属性名作为name。通过name找不到的话会自动启动通过类型byType装配。@Autowired注解默认根据类型装配byType,如果想根据名称装配,需要配合@Qualifier注解一起用。
(3)@Resource注解用在属性上、setter方法上。- @Autowired注解用在属性上、setter方法上、构造方法上、构造方法参数上。
@Resource注解属于JDK扩展包,所以不在JDK当中,需要额外引入以下依赖,如果是JDK8的话不需要额外引入依赖。高于JDK11或低于JDK8需要引入以下依赖。
<dependency>
<groupId>jakarta.annotation</groupId>
<artifactId>jakarta.annotation-api</artifactId>
<version>2.1.1</version>
</dependency>
UserController类:
public class UserController {
//根据名称进行注入(指定名称)
@Resource(name = "myUserService")
private UserService userService;
public void add(){
System.out.println("controller执行。。。");
userService.add();
}
}
UserServiceImpl类(实现UserService接口):
@Service("myUserService")
public class UserServiceImpl implements UserService {
//不指定名称,根据属性名字进行匹配
@Resource
private UserDao myUserDao;
@Override
public void add() {
System.out.println("service执行。。。");
myUserDao.add();
}
}
UserDaoImpl类(实现UserDao接口):
@Repository(value = "myUserDao")
public class UserDaoImpl implements UserDao {
@Override
public void add() {
System.out.println("dao执行。。。");
}
}
测试结果:
注:@Resource注解:默认byName注入,没有指定name时把属性名当做name,根据name找不到时,才会byType注入。byType注入时,某种类型的Bean只能有一个。
2.3.5、 Spring全注解开发
全注解开发就是不再使用spring配置文件了,写一个配置类来代替配置文件。
创建一个配置类:
@Configuration //配置类
@ComponentScan("com.atguigu.spring6") //开启组件扫描
public class SpringConfig {
}
则测试代码:
public class Test {
public static void main(String[] args) {
ApplicationContext context =
new AnnotationConfigApplicationContext(SpringConfig.class);
UserController userController = context.getBean(UserController.class);
userController.add();
}
}
输出结果:
3、原理-手写IoC
3.1、 回顾Java反射
Java反射机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意方法和属性;这种动态获取信息以及动态调用对象方法的功能称为Java语言的反射机制。简单来说,反射机制指的是程序在运行时能够获取自身的信息。
要想解剖一个类,必须先要获取到该类的Class对象(即字节码文件)。而剖析一个类或用反射解决具体的问题就是使用相关API(1)java.lang.Class(2)java.lang.reflect,所以,Class对象是反射的根源。
3.1.1、 获取Class对象的多种方式
@Test
public void test01() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
//1 类名.class
Class clazz1 = Car.class;
//2 对象.getClass()
Class clazz2 = new Car().getClass();
//3 Class.forName("全路径")
Class clazz3 = Class.forName("com.atguigu.reflect.Car");
//实例化
Car car = (Car)clazz3.getDeclaredConstructor().newInstance();
System.out.println(clazz1);
System.out.println(clazz2);
System.out.println(car);
}
运行结果:
3.1.2、 获取构造方法并实例化对象
创建一个新的Test方法并在内部做测试
获取所有构造
Class clazz = Car.class;
//获取所有构造
//getConstructors()获取所有public的构造方法
//Constructor[] constructors = clazz.getConstructors();
//getDeclaredConstructors()获取所有的构造方法
Constructor[] constructors = clazz.getDeclaredConstructors();
for (Constructor c:constructors)
System.out.println("构造方法名称:"+c.getName()+" 构造方法的参数个数:"+c.getParameterCount());
输出结果:
指定有参数构造创建对象
1 构造public
Constructor c1 =
clazz.getConstructor(String.class, int.class, String.class);
Car car1 = (Car)c1.newInstance("夏利", 10, "红色");
System.out.println("public修饰构造器:"+ car1);
输出结果:
2 构造private
Constructor c2 = clazz.getDeclaredConstructor(String.class, int.class, String.class);
c2.setAccessible(true); //设置允许访问
Car car2 = (Car)c2.newInstance("奔驰", 20, "黑色");
System.out.println("private修饰构造器:" + car2);
输出结果:
3.1.3、 获取属性
创建一个新的Test方法并在内部进行测试
Class clazz = Car.class;
Car car = (Car)clazz.getDeclaredConstructor().newInstance(); //实例化
//获取所有public属性
//Field[] field = clazz.getFields();
//获取所有属性包括private
Field[] fields = clazz.getDeclaredFields();
for (Field field:fields){
if(field.getName().equals("name")){
field.setAccessible(true); //设置允许访问
field.set(car,"奔驰");
}
System.out.println(field.getName()); //获取属性名
System.out.println(car);
}
输出结果:
3.1.4、 获取方法
创建一个新的Test方法并在其内部进行测试
@Test
public void test04() throws Exception {
Car car = new Car("奔驰", 10, "黑色");
Class clazz = car.getClass();
//1 public方法
Method[] methods = clazz.getMethods();
for (Method m1:methods){
//System.out.println(m1.getName());
//执行toString方法
if (m1.getName().equals("toString")){
String invoke = (String)m1.invoke(car);
System.out.println("toString方法执行:" + invoke);
}
}
//2 private方法
Method[] methodsAll = clazz.getDeclaredMethods();
for (Method m:methodsAll){
//执行private修饰的run方法
if(m.getName().equals("run")){
m.setAccessible(true); //设置允许执行
m.invoke(car);
}
}
}
输出结果:
4、面向切面:AOP
4.1、 AOP概念及相关术语
4.1.1、 概述
AOP(Aspect Oriented Programming)是一种设计思想,是软件设计领域中的面向切面编程,它是面向对象编程的一种补充和完善,它以通过预编译方式和运行期动态代理方式实现,在不修改源代码的情况下,给程序动态统一添加额外功能的一种技术。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。
4.1.2、 相关术语
(1)横切关注点
分散在每个各个模块中解决同一样的问题,如用户验证、日志管理、事务处理、数据缓存都属于横切关注点。
从每个方法中抽取出来的同一类非核心业务。在同一个项目中,我们可以使用多个横切关注点对相关方法进行多个不同方面的增强。
这个概念不是语法层面的,而是根据附加功能的逻辑上的需要:有十个附加功能,就有十个横切关注点。
(2)通知(增强)
增强,通俗说,就是你想要增强的功能,比如 安全,事务,日志等。
每一个横切关注点上要做的事情都需要写一个方法来实现,这样的方法就叫通知方法。
- 前置通知:在被代理的目标方法前执行
- 返回通知:在被代理的目标方法成功结束后执行(寿终正寝)
- 异常通知:在被代理的目标方法异常结束后执行(死于非命)
- 后置通知:在被代理的目标方法最终结束后执行(盖棺定论)
- 环绕通知:使用try…catch…finally结构围绕整个被代理的目标方法,包括上面四种通知对应的所有位置。
(3)切面
封装通知方法的类。
(4)目标
被代理的目标对象。
(5)代理
向目标对象应用通知之后创建的代理对象。
(6)连接点
这也是一个纯逻辑概念,不是语法定义的。
把方法排成一排,每一个横切位置看成x轴方向,把方法从上到下执行的顺序看成y轴,x轴和y轴的交叉点就是连接点。通俗说,就是spring允许你使用通知的地方
(7)切入点
定位连接点的方式。
每个类的方法中都包含多个连接点,所以连接点是类中客观存在的事物(从逻辑上来说)。
如果把连接点看作数据库中的记录,那么切入点就是查询记录的 SQL 语句。
Spring 的 AOP 技术可以通过切入点定位到特定的连接点。通俗说,要实际去增强的方法
4.1.3、 作用
- 简化代码
把方法中固定位置的重复的代码抽取出来,让被抽取的方法更专注于自己的核心功能,提高内聚性。
- 代码增强
把特定的功能封装到切面类中,看哪里有需要,就往上套,被套用了切面逻辑的方法就被切面给增强了。
4.2、 基于注解的AOP
4.2.1、 技术说明
- 动态代理分为JDK动态代理和cglib动态代理
- 当目标类有接口的情况使用JDK动态代理和cglib动态代理,没有接口时只能使用cglib动态代理
- JDK动态代理动态生成的代理类会在com.sun.proxy包下,类名为$proxy1,和目标类实现相同的接口
- cglib动态代理动态生成的代理类会和目标在在相同的包下,会继承目标类
- 动态代理(InvocationHandler):JDK原生的实现方式,需要被代理的目标类必须实现接口。因为这个技术要求代理对象和目标对象实现同样的接口(兄弟两个拜把子模式)。
- cglib:通过继承被代理的目标类(认干爹模式)实现代理,所以不需要目标类实现接口。
- AspectJ:是AOP思想的一种实现。本质上是静态代理,将代理逻辑“织入”被代理的目标类编译得到的字节码文件,所以最终效果是动态的。weaver就是织入器。Spring只是借用了AspectJ中的注解。
4.2.2、 创建切面类并配置
在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"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 开启组件扫描-->
<context:component-scan base-package="com.atguigu.spring6.aop.annoaop"></context:component-scan>
<!-- 开启aspect自动代理,为目标对象生成代理-->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>
创建一个切面类,如下:
@Aspect //切面类
@Component //ioc容器
public class LogAspect {
//设置切入点和通知类型
//通知类型:前置 返回 异常 后置 环绕
// 前置 @Before(value="切入点表达式配置切入点")
@Before(value = "execution(public int com.atguigu.spring6.aop.annoaop.CalculatorImpl.*(..))")
public void beforeMethod(JoinPoint joinPoint) {
//获得方法名称
String name = joinPoint.getSignature().getName();
//获取参数
Object[] args = joinPoint.getArgs();
System.out.println("Logger-->前置通知,方法名称:" + name + ",参数:" + Arrays.toString(args));
}
//返回@AfterReturning
//res为返回结果,名字需一致
@AfterReturning(value = "execution(* com.atguigu.spring6.aop.annoaop.*.*(..))" , returning = "res")
public void afterReturningMethod(JoinPoint joinPoint, Object res){
String name = joinPoint.getSignature().getName();
System.out.println("Logger-->返回通知,方法名称:" + name + ",返回结果:" + res);
}
// 异常@AfterThrowing 获取到目标方法异常信息
//目标出现异常,这个通知执行
//ex为异常信息,前后名字需一致
@AfterThrowing(value = "execution(* com.atguigu.spring6.aop.annoaop.*.*(..))",throwing = "ex")
public void afterThrowingMethod(JoinPoint joinPoint, Throwable ex){
String name = joinPoint.getSignature().getName();
System.out.println("Logger-->异常通知,方法名称:" + name + ",异常信息:" + ex);
}
// 后置@After()
@After(value = "execution(* com.atguigu.spring6.aop.annoaop.*.*(..))")
public void afterMethod(JoinPoint joinPoint){
//获得方法名称
String name = joinPoint.getSignature().getName();
//获取参数
Object[] args = joinPoint.getArgs();
System.out.println("Logger-->后置通知,方法名称:" + name + ",参数:" + Arrays.toString(args));
}
// 环绕@Around()
@Around(value = "execution(* com.atguigu.spring6.aop.annoaop.*.*(..))")
public Object aroundMethod(ProceedingJoinPoint joinPoint){
String name = joinPoint.getSignature().getName();
Object[] args = joinPoint.getArgs();
String argString = Arrays.toString(args);
//System.out.println("Logger-->环绕通知,方法名称:" + name + ",参数:" + Arrays.toString(args));
Object res = null;
try {
System.out.println("环绕通知==目标方法之前执行");
//调用目标方法
res = joinPoint.proceed();
System.out.println("环绕通知==目标方法返回值之后执行");
}catch (Throwable throwable) {
throwable.printStackTrace();
System.out.println("环绕通知==目标方法出现异常执行");
}finally {
System.out.println("环绕通知==目标方法执行完毕执行");
}
return res;
}
}
结果:
当调用函数出现异常时,才会进行一场通知。
4.2.3、 各种通知
- 前置通知:使用@Before注解标识,在被代理的目标方法前执行
- 返回通知:使用@AfterReturning注解标识,在被代理的目标方法成功结束后执行(寿终正寝)
- 异常通知:使用@AfterThrowing注解标识,在被代理的目标方法异常结束后执行(死于非命)
- 后置通知:使用@After注解标识,在被代理的目标方法最终结束后执行(盖棺定论)
- 环绕通知:使用@Around注解标识,使用try…catch…finally结构围绕整个被代理的目标方法,包括上面四种通知对应的所有位置
4.2.4、 切入点表达式语法
(1)用号代替“权限修饰符”和“返回值”部分表示“权限修饰符”和“返回值”不限
(2)在包名的部分,一个“”号只能代表包的层次结构中的一层,表示这一层是任意的。
例如:.Hello匹配com.Hello,不匹配com.atguigu.Hello
(3)在包名的部分,使用“…”表示包名任意、包的层次深度任意
(4)在类名的部分,类名部分整体用号代替,表示类名任意
(5)在类名的部分,可以使用号代替类名的一部分
例如:Service匹配所有名称以Service结尾的类或接口
(6)在方法名部分,可以使用号表示方法名任意
(7)在方法名部分,可以使用*号代替方法名的一部分
例如:*Operation匹配所有方法名以Operation结尾的方法
(8)在方法参数列表部分,使用(…)表示参数列表任意
(9)在方法参数列表部分,使用(int,…)表示参数列表以一个int类型的参数开头
(10)在方法参数列表部分,基本数据类型和对应的包装类型是不一样的
(11)切入点表达式中使用 int 和实际方法中 Integer 是不匹配的
(12)在方法返回值部分,如果想要明确指定一个返回值类型,那么必须同时写明权限修饰符
4.2.5、 重用切入点表达式
声明:
@Pointcut("execution(* com.atguigu.aop.annotation.*.*(..))")
public void pointCut(){}
在同一个切面中使用:
@Before("pointCut()")
public void beforeMethod(JoinPoint joinPoint){
String methodName = joinPoint.getSignature().getName();
String args = Arrays.toString(joinPoint.getArgs());
System.out.println("Logger-->前置通知,方法名:"+methodName+",参数:"+args);
}
在不同切面中使用:
@Before("com.atguigu.aop.CommonPointCut.pointCut()")
public void beforeMethod(JoinPoint joinPoint){
String methodName = joinPoint.getSignature().getName();
String args = Arrays.toString(joinPoint.getArgs());
System.out.println("Logger-->前置通知,方法名:"+methodName+",参数:"+args);
}
4.2、 基于XML的AOP
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"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 开启组件的扫描-->
<context:component-scan base-package="com.atguigu.spring6.aop.xmlaop"></context:component-scan>
<!-- 配置aop五种通知类型-->
<aop:config>
<!-- 配置切面类-->
<aop:aspect ref="logAspect">
<!-- 配置切入点-->
<aop:pointcut id="pointcut" expression="execution(* com.atguigu.spring6.aop.xmlaop.*.*(..))"/>
<!-- 配置五种通知类型-->
<!-- 前置通知-->
<aop:before method="beforeMethod" pointcut-ref="pointcut"></aop:before>
<!-- 后置通知-->
<aop:after method="afterMethod" pointcut-ref="pointcut"></aop:after>
<!-- 返回通知-->
<aop:after-returning method="afterReturningMethod" returning="res" pointcut-ref="pointcut"></aop:after-returning>
<!-- 异常通知-->
<aop:after-throwing method="afterThrowingMethod" throwing="ex" pointcut-ref="pointcut"></aop:after-throwing>
<!-- 环绕通知 -->
<aop:around method="aroundMethod" pointcut-ref="pointcut"></aop:around>
</aop:aspect>
</aop:config>
</beans>
5、 单元测试:JUnit
在之前的测试方法中,几乎都能看到以下的两行代码:
ApplicationContext context = new ClassPathXmlApplicationContext("xxx.xml");
Xxxx xxx = context.getBean(Xxxx.class);
这两行代码的作用是创建Spring容器,最终获取到对象,但是每次测试都需要重复编写。针对上述问题,我们需要的是程序能自动帮我们创建容器。我们都知道JUnit无法知晓我们是否使用了 Spring 框架,更不用说帮我们创建 Spring 容器了。Spring提供了一个运行器,可以读取配置文件(或注解)来创建容器。我们只需要告诉它配置文件位置就可以了。这样一来,我们通过Spring整合JUnit可以使程序创建spring容器了。
5.1、 整合JUnit5
创建一个User类:
@Component
public class User {
public void run() {
System.out.println("user run....");
}
}
配置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"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<context:component-scan base-package="com.atguigu.spring6.junit"></context:component-scan>
</beans>
创建一个测试类并进测试:
@SpringJUnitConfig(locations = "classpath:bean.xml")
public class SpringTestJunit5 {
//注入
@Autowired
private User user;
@Test
public void testUser() {
System.out.println(user);
user.run();
}
}
测试结果:
5.2、 整合JUnit4
测试类:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:bean.xml")
public class SpringTestJunit4 {
@Autowired
private User user;
@Test
public void testUser(){
System.out.println(user);
user.run();
}
}
运行结果:
注:Junit4使用的@Test是import org.junit.Test依赖,Junit5使用的@Test是import org.junit.jupiter.api.Test依赖。
6、事务
6.1、 JdbcTemplate
Spring 框架对 JDBC 进行封装,使用 JdbcTemplate 方便实现对数据库操作。
6.1.1、 准备工作
(1)添加相关依赖。
(2)创建jdbc.properties:填写你的mysql的用户和密码,确保都一致。
jdbc.user=root
jdbc.password=root
jdbc.url=jdbc:mysql://localhost:3306/spring?characterEncoding=utf8&useSSL=false
jdbc.driver=com.mysql.cj.jdbc.Driver
(3)配置beans.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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 引入外部属性文件,创建数据源对象-->
<context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>
<bean id="druidDataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="url" value="${jdbc.url}"></property>
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="username" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<!-- 创建jdbcTemplate对象,注入数据源-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="druidDataSource"></property>
</bean>
</beans>
(5)创建一个名为spring的数据库,并在里面运行sql语句生成一个表格,本人使用的是Navicat连接的Mysql。
CREATE TABLE `t_emp` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) DEFAULT NULL COMMENT '姓名',
`age` int(11) DEFAULT NULL COMMENT '年龄',
`sex` varchar(2) DEFAULT NULL COMMENT '性别',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
6.1.2、 实现CURD
(1)装配 JdbcTemplate
创建测试类,整合JUnit,注入JdbcTemplate
@SpringJUnitConfig(locations = "classpath:beans.xml")
public class JDBCTemplateTest {
@Autowired
private JdbcTemplate jdbcTemplate;
}
(2)创建一个Emp类,包含以下属性,并重写toString方法,设置get、set方法。
private Integer id;
private String name;
private Integer age;
private String sex;
(3)测试添加、修改、删除操作操作
以下测试全部在(1)创建的测试类进行
@Test
public void testUpdate() {
//1 添加操作
//第一步 编写sql语句
// String sql = "insert into t_emp values(null,?,?,?)";
// //第二部 调用jdbcTemplate的方法,传入相关参数,返回的是影响行数
// int rows = jdbcTemplate.update(sql, "林平之", 20, "未知");
// System.out.println(rows);
// //2 修改操作
// String sql = "update t_emp set name=? where id=?";
// int rows = jdbcTemplate.update(sql, "林平之atguigu", 3);
// System.out.println(rows);
//3 删除操作
String sql = "delete from t_emp where id=?";
int rows = jdbcTemplate.update(sql, 3);
System.out.println(rows);
}
(4)测试查询操作
- 查询:返回对象
@Test
public void testSelectObject() {
//写法一
// String sql = "select * from t_emp where id=?";
// Emp empResult = jdbcTemplate.queryForObject(sql, (rs, rowNum) -> {
// Emp emp = new Emp();
// emp.setId(rs.getInt("id"));
// emp.setName(rs.getString("name"));
// emp.setAge(rs.getInt("age"));
// emp.setSex(rs.getString("sex"));
// return emp;
// }, 1);
// System.out.println(empResult);
//写法二
//写法一是写法二的复现,底层思路一致
String sql = "select * from t_emp where id=?";
Emp emp = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(Emp.class), 2);
System.out.println(emp);
}
结果:
- 查询:返回list集合
@Test
public void testSelectList() {
String sql = "select * from t_emp";
List<Emp> list =
jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Emp.class));
System.out.println(list);
}
结果:
- 查询:返回单个值
@Test
public void testSelectValue() {
//查询数据条数
String sql = "select count(*) from t_emp";
Integer count = jdbcTemplate.queryForObject(sql, Integer.class);
System.out.println(count);
}
结果:
6.2、 声明式事务概念
6.2.1、 事务基本概念
(1)什么是事务
数据库事务( transaction)是访问并可能操作各种数据项的一个数据库操作序列,这些操作要么全部执行,要么全部不执行,是一个不可分割的工作单位。事务由事务开始与事务结束之间执行的全部数据库操作组成。
(2)事务的特性
- A:原子性(Atomicity)
事务的一致性指的是在一个事务执行之前和执行之后数据库都必须处于一致性状态。如果事务成功地完成,那么系统中所有变化将正确地应用,系统处于有效状态。如果在事务中出现错误,那么系统中的所有变化将自动地回滚,系统返回到原始状态。 - C:一致性(Consistency)
事务的一致性指的是在一个事务执行之前和执行之后数据库都必须处于一致性状态。如果事务成功地完成,那么系统中所有变化将正确地应用,系统处于有效状态。如果在事务中出现错误,那么系统中的所有变化将自动地回滚,系统返回到原始状态。 - I:隔离性(Isolation)
指的是在并发环境中,当不同的事务同时操纵相同的数据时,每个事务都有各自的完整数据空间。由并发事务所做的修改必须与任何其他并发事务所做的修改隔离。事务查看数据更新时,数据所处的状态要么是另一事务修改它之前的状态,要么是另一事务修改它之后的状态,事务不会查看到中间状态的数据。 - D:持久性(Durability)
指的是只要事务成功结束,它对数据库所做的更新就必须保存下来。即使发生系统崩溃,重新启动数据库系统后,数据库还能恢复到事务成功结束时的状态。
6.2.2、 声明式事务
事务控制的代码有规律可循,代码的结构基本是确定的,所以框架就可以将固定模式的代码抽取出来,进行相关的封装。封装起来后,我们只需要在配置文件中进行简单的配置即可完成操作。
- 好处1:提高开发效率
- 好处2:消除了冗余的代码
- 好处3:框架会综合考虑相关领域中在实际开发环境下有可能遇到的各种问题,进行了健壮性、性能等各个方面的优化
6.3、 基于注解的声明式事务
6.3.1、 准备工作
在beans.xml添加配置
<!--扫描组件-->
<context:component-scan base-package="com.atguigu.spring6"></context:component-scan>
创建mysql的两个表,执行sql代码:
CREATE TABLE `t_book` (
`book_id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
`book_name` varchar(20) DEFAULT NULL COMMENT '图书名称',
`price` int(11) DEFAULT NULL COMMENT '价格',
`stock` int(10) unsigned DEFAULT NULL COMMENT '库存(无符号)',
PRIMARY KEY (`book_id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
insert into `t_book`(`book_id`,`book_name`,`price`,`stock`) values (1,'斗破苍穹',80,100),(2,'斗罗大陆',50,100);
CREATE TABLE `t_user` (
`user_id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
`username` varchar(20) DEFAULT NULL COMMENT '用户名',
`balance` int(10) unsigned DEFAULT NULL COMMENT '余额(无符号)',
PRIMARY KEY (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
insert into `t_user`(`user_id`,`username`,`balance`) values (1,'admin',50);
创建BookController:
@Controller
public class BookController {
@Autowired
private BookService bookService;
public void buyBook(Integer bookId, Integer userId){
bookService.buyBook(bookId, userId);
}
}
创建接口BookService:
package com.atguigu.spring6.service;
public interface BookService {
void buyBook(Integer bookId, Integer userId);
}
创建实现类BookServiceImpl:
@Service
public class BookServiceImpl implements BookService {
@Autowired
private BookDao bookDao;
@Override
public void buyBook(Integer bookId, Integer userId) {
//查询图书的价格
Integer price = bookDao.getPriceByBookId(bookId);
//更新图书的库存
bookDao.updateStock(bookId);
//更新用户的余额
bookDao.updateBalance(userId, price);
}
}
创建接口BookDao:
package com.atguigu.spring6.dao;
public interface BookDao {
Integer getPriceByBookId(Integer bookId);
void updateStock(Integer bookId);
void updateBalance(Integer userId, Integer price);
}
创建实现类BookDaoImpl:
@Repository
public class BookDaoImpl implements BookDao {
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public Integer getPriceByBookId(Integer bookId) {
String sql = "select price from t_book where book_id = ?";
return jdbcTemplate.queryForObject(sql, Integer.class, bookId);
}
@Override
public void updateStock(Integer bookId) {
String sql = "update t_book set stock = stock - 1 where book_id = ?";
jdbcTemplate.update(sql, bookId);
}
@Override
public void updateBalance(Integer userId, Integer price) {
String sql = "update t_user set balance = balance - ? where user_id = ?";
jdbcTemplate.update(sql, price, userId);
}
}
创建测试类并测试:
@SpringJUnitConfig(locations = "classpath:beans.xml")
public class TxByAnnotationTest {
@Autowired
private BookController bookController;
@Test
public void testBuyBook(){
bookController.buyBook(1, 1);
}
}
6.3.2、 加入事务
在beans增加配置:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="druidDataSource"></property>
</bean>
<!--
开启事务的注解驱动
通过注解@Transactional所标识的方法或标识的类中所有的方法,都会被事务管理器管理事务
-->
<!-- transaction-manager属性的默认值是transactionManager,如果事务管理器bean的id正好就是这个默认值,则可以省略这个属性 -->
<tx:annotation-driven transaction-manager="transactionManager" />
因为service层表示业务逻辑层,一个方法表示一个完成的功能,因此处理事务一般在service层处理在BookServiceImpl的buybook()添加注解@Transactional。
6.3.3、 @Transactional注解标识的位置
@Transactional标识在方法上,则只会影响该方法。
@Transactional标识的类上,则会影响类中所有的方法。
6.3.4、 事务属性:只读
对一个查询操作来说,如果我们把它设置成只读,就能够明确告诉数据库,这个操作不涉及写操作。这样数据库就能够针对查询操作来进行优化。
@Transactional(readOnly = true)
运行结果;
6.3.5、 事务属性:超时
事务在执行过程中,有可能因为遇到某些问题,导致程序卡住,从而长时间占用数据库资源。而长时间占用资源,大概率是因为程序运行出现了问题(可能是Java程序或MySQL数据库或网络连接等等)。此时这个很可能出问题的程序应该被回滚,撤销它已做的操作,事务结束,把资源让出来,让其他正常程序可以执行。概括来说就是一句话:超时回滚,释放资源。
@Service
@Transactional(timeout = 3)
public class BookServiceImpl implements BookService{
@Autowired
private BookDao bookDao;
//买书
@Override
public void buyBook(Integer bookId,Integer userId){
//TODO 模拟超时效果
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
//根据图书id查询图书价格
Integer price = bookDao.getBookPriceBuyBookId(bookId);
//更新图书表 库存量-1
bookDao.updateStock(bookId);
//更新用户表用户余额 -图书价格
bookDao.updateUserBalance(userId,price);
}
}
运行结果:
6.3.6、 事务属性:回滚策略
声明式事务默认只针对运行时异常回滚,编译时异常不回滚。可以通过@Transactional中相关属性设置回滚策略。
- rollbackFor属性:需要设置一个Class类型的对象。
- rollbackForClassName属性:需要设置一个字符串类型的全类名。
- noRollbackFor属性:需要设置一个Class类型的对象。
- noRollbackForClassName属性:需要设置一个字符串类型的全类名。
@Transactional(noRollbackFor = ArithmeticException.class)
表示出现ArithmeticException异常不进行回滚。
6.3.7、 事务属性:隔离级别
数据库系统必须具有隔离并发运行各个事务的能力,使它们不会相互影响,避免各种并发问题。一个事务与其他事务隔离的程度称为隔离级别。SQL标准中规定了多种事务隔离级别,不同隔离级别对应不同的干扰程度,隔离级别越高,数据一致性就越好,但并发性越弱。
隔离级别一共有四种:
- 读未提交:READ UNCOMMITTED,允许Transaction01读取Transaction02未提交的修改。
- 读已提交:READ COMMITTED,要求Transaction01只能读取Transaction02已提交的修改。
- 可重复读:REPEATABLE READ,确保Transaction01可以多次从一个字段中读取到相同的值,即Transaction01执行期间禁止其它事务对这个字段进行更新。
- 串行化:SERIALIZABLE,确保Transaction01可以多次从一个表中读取到相同的行,在Transaction01执行期间,禁止其它事务对这个表进行添加、更新、删除操作。可以避免任何并发问题,但性能十分低下。
各个隔离级别解决并发问题的能力见下表:
各种数据库产品对事务隔离级别的支持程度:
使用方法:
@Transactional(isolation = Isolation.DEFAULT)//使用数据库默认的隔离级别
@Transactional(isolation = Isolation.READ_UNCOMMITTED)//读未提交
@Transactional(isolation = Isolation.READ_COMMITTED)//读已提交
@Transactional(isolation = Isolation.REPEATABLE_READ)//可重复读
@Transactional(isolation = Isolation.SERIALIZABLE)//串行化
6.3.8、 事务属性:传播行为
什么是事务的传播行为?
在service类中有a()方法和b()方法,a()方法上有事务,b()方法上也有事务,当a()方法执行过程中调用了b()方法,事务是如何传递的?合并到一个事务里?还是开启一个新的事务?这就是事务传播行为。
一共有七种传播行为:
- REQUIRED:支持当前事务,如果不存在就新建一个(默认)【没有就新建,有就加入】。
- SUPPORTS:支持当前事务,如果当前没有事务,就以非事务方式执行**【有就加入,没有就不管了】**。
- MANDATORY:必须运行在一个事务中,如果当前没有事务正在发生,将抛出一个异常**【有就加入,没有就抛异常】**。
- REQUIRES_NEW:开启一个新的事务,如果一个事务已经存在,则将这个存在的事务挂起**【不管有没有,直接开启一个新事务,开启的新事务和之前的事务不存在嵌套关系,之前事务被挂起】**。
- NOT_SUPPORTED:以非事务方式运行,如果有事务存在,挂起当前事务**【不支持事务,存在就挂起】**
- NEVER:以非事务方式运行,如果有事务存在,抛出异常**【不支持事务,存在就抛异常】**。
- NESTED:如果当前正有一个事务在进行中,则该方法应当运行在一个嵌套式事务中。被嵌套的事务可以独立于外层事务进行提交或回滚。如果外层事务不存在,行为就像REQUIRED一样。【有事务的话,就在这个事务里再嵌套一个完全独立的事务,嵌套的事务可以独立的提交和回滚。没有事务就和REQUIRED一样。】
6.3.9、 全注解配置事务
创建一个Config配置类用于代替bean.xml
@Configuration //配置类
@ComponentScan("com.atguigu.spring6.tx")//组件扫描
@EnableTransactionManagement //开始事务管理
public class SpringConfig {
//创建数据源
@Bean
public DataSource getDataSource() {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUsername("root");
dataSource.setPassword("zmh0527!");
dataSource.setUrl("jdbc:mysql://localhost:3306/spring?characterEncoding=utf8&useSSL=false");
return dataSource;
}
//JdbcTemplate注入数据源
@Bean(name = "jdbcTemplate")
public JdbcTemplate getJdbcTemplate(DataSource dataSource) {
JdbcTemplate jdbcTemplate = new JdbcTemplate();
jdbcTemplate.setDataSource(dataSource);
return jdbcTemplate;
}
//事务管理器注入数据源
@Bean
public DataSourceTransactionManager getDataSourceTransactionManager(DataSource dataSource){
DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
dataSourceTransactionManager.setDataSource(dataSource);
return dataSourceTransactionManager;
}
}
7、 资源操作:Resources
7.1、概述
Java的标准java.net.URL类和各种URL前缀的标准处理程序无法满足所有对low-level资源的访问,比如:没有标准化的 URL 实现可用于访问需要从类路径或相对于 ServletContext 获取的资源。并且缺少某些Spring所需要的功能,例如检测某资源是否存在等。而Spring的Resource声明了访问low-level资源的能力。
Spring 的 Resource 接口位于 org.springframework.core.io 中。 旨在成为一个更强大的接口,用于抽象对低级资源的访问。
Resource接口继承了InputStreamSource接口,提供了很多InputStreamSource所没有的方法。
其中一些重要的方法:
- getInputStream(): 找到并打开资源,返回一个InputStream以从资源中读取。预计每次调用都会返回一个新的InputStream(),调用者有责任关闭每个流
- exists(): 返回一个布尔值,表明某个资源是否以物理形式存在
- isOpen: 返回一个布尔值,指示此资源是否具有开放流的句柄。如果为true,InputStream就不能够多次读取,只能够读取一次并且及时关闭以避免内存泄漏。对于所有常规资源实现,返回false,但是InputStreamResource除外。
- getDescription(): 返回资源的描述,用来输出错误的日志。这通常是完全限定的文件名或资源的实际URL。
其他方法:
- isReadable(): 表明资源的目录读取是否通过getInputStream()进行读取。
- isFile(): 表明这个资源是否代表了一个文件系统的文件。
- getURL(): 返回一个URL句柄,如果资源不能够被解析为URL,将抛出IOException
- getURI(): 返回一个资源的URI句柄
- getFile(): 返回某个文件,如果资源不能够被解析称为绝对路径,将会抛出FileNotFoundException
- lastModified(): 资源最后一次修改的时间戳
- createRelative(): 创建此资源的相关资源
- getFilename(): 资源的文件名是什么 例如:最后一部分的文件名 myfile.txt
7.2、 Resource的实现类
Resource 接口是 Spring 资源访问策略的抽象,它本身并不提供任何资源访问实现,具体的资源访问由该接口的实现类完成——每个实现类代表一种资源访问策略。Resource一般包括这些实现类:UrlResource、ClassPathResource、FileSystemResource、ServletContextResource、InputStreamResource、ByteArrayResource
7.2.1、UrlResource访问网络资源
Resource的一个实现类,用来访问网络资源,它支持URL的绝对路径。
http:------该前缀用于访问基于HTTP协议的网络资源。
ftp:------该前缀用于访问基于FTP协议的网络资源
file: ------该前缀用于从文件系统中读取资源
创建一个新的文件,并创建一个类:
//演示UrlResource访问网络资源
public class UrlResourceDemo {
public static void main(String[] args) {
//http前缀
// loadUrlResource("http://www.baidu.com");
//file前缀(该文件需要在根目录下创建)
loadUrlResource("file:test.txt");
}
//访问前缀http
public static void loadUrlResource(String path) {
try {
//创建Resource实现类的对象 UrlResource
UrlResource url = new UrlResource(path);
//获取资源信息
System.out.println(url.getFilename());
try {
System.out.println(url.getURI());
} catch (IOException e) {
throw new RuntimeException(e);
}
System.out.println(url.getDescription());
try {
System.out.println(url.getInputStream().read());
} catch (IOException e) {
throw new RuntimeException(e);
}
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
}
运行结果:
7.2.2、 ClassPathResource 访问类路径下资源
ClassPathResource 用来访问类加载路径下的资源,相对于其他的 Resource 实现类,其主要优势是方便访问类加载路径里的资源,尤其对于 Web 应用,ClassPathResource 可自动搜索位于 classes 下的资源文件,无须使用绝对路径访问。
创建一个类:
public class ClassPathResourceDemo {
public static void loadClasspathResource(String path) {
//创建对象ClassPathResource
ClassPathResource resource = new ClassPathResource(path);
System.out.println(resource.getFilename());
System.out.println(resource.getDescription());
//获取文件内容
try {
InputStream inputStream = resource.getInputStream();
byte[] b = new byte[1024];
while (inputStream.read(b)!=-1){
System.out.println(new String(b));
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) {
//该文件在所在类目录下的resources文件下创建
loadClasspathResource("test.txt");
}
}
运行结果:
7.2.3、 FileSystemResource 访问文件系统资源
Spring 提供的 FileSystemResource 类用于访问文件系统资源,使用 FileSystemResource 来访问文件系统资源并没有太大的优势,因为 Java 提供的 File 类也可用于访问文件系统资源。
//访问系统资源(可以用绝对路径和相对路径)
public class FileSystemResourceDemo {
public static void loadFileResource(String path){
//创建对象
FileSystemResource resource = new FileSystemResource(path);
System.out.println(resource.getFilename());
System.out.println(resource.getDescription());
try {
InputStream inputStream = resource.getInputStream();
byte[] b = new byte[1024];
while (inputStream.read(b)!=-1){
System.out.println(new String(b));
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) {
//绝对路径
//loadFileResource("/Users/zmhgogogo/Desktop/test.txt");
//相对路径
loadFileResource("test.txt");
}
}
测试结果:
7.2.4、 ServletContextResource
这是ServletContext资源的Resource实现,它解释相关Web应用程序根目录中的相对路径。它始终支持流(stream)访问和URL访问,但只有在扩展Web应用程序存档且资源实际位于文件系统上时才允许java.io.File访问。无论它是在文件系统上扩展还是直接从JAR或其他地方(如数据库)访问,实际上都依赖于Servlet容器。
7.2.5、 InputStreamResource
InputStreamResource 是给定的输入流(InputStream)的Resource实现。它的使用场景在没有特定的资源实现的时候使用(感觉和@Component 的适用场景很相似)。与其他Resource实现相比,这是已打开资源的描述符。 因此,它的isOpen()方法返回true。如果需要将资源描述符保留在某处或者需要多次读取流,请不要使用它。
7.2.6、
字节数组的Resource实现类。通过给定的数组创建了一个ByteArrayInputStream。它对于从任何给定的字节数组加载内容非常有用,而无需求助于单次使用的InputStreamResource。
7.3、 ResourceLoader 接口
7.3.1、 ResourceLoader 概述
Spring 提供如下两个标志性接口:
(1)ResourceLoader : 该接口实现类的实例可以获得一个Resource实例。
(2) ResourceLoaderAware : 该接口实现类的实例将获得一个ResourceLoader的引用。
在ResourceLoader接口里有如下方法:
(1)Resource getResource(String location) : 该接口仅有这个方法,用于返回一个Resource实例。ApplicationContext实现类都实现ResourceLoader接口,因此ApplicationContext可直接获取Resource实例。
@Test
public void demo1() {
ApplicationContext context = new ClassPathXmlApplicationContext();
Resource res = context.getResource("test.txt");
System.out.println(resource.getFilename());
}
运行结果:
7.3.2、 ResourceLoader 总结
Spring将采用和ApplicationContext相同的策略来访问资源。也就是说,如果ApplicationContext是FileSystemXmlApplicationContext,res就是FileSystemResource实例;如果ApplicationContext是ClassPathXmlApplicationContext,res就是ClassPathResource实例
当Spring应用需要进行资源访问时,实际上并不需要直接使用Resource实现类,而是调用ResourceLoader实例的getResource()方法来获得资源,ReosurceLoader将会负责选择Reosurce实现类,也就是确定具体的资源访问策略,从而将应用程序和具体的资源访问策略分离开来
另外,使用ApplicationContext访问资源时,可通过不同前缀指定强制使用指定的ClassPathResource、FileSystemResource等实现类
Resource res = ctx.getResource("calsspath:bean.xml");
Resrouce res = ctx.getResource("file:bean.xml");
Resource res = ctx.getResource("http://localhost:8080/beans.xml");
7.4、 ResourceLoaderAware 接口
ResourceLoaderAware接口实现类的实例将获得一个ResourceLoader的引用,ResourceLoaderAware接口也提供了一个setResourceLoader()方法,该方法将由Spring容器负责调用,Spring容器会将一个ResourceLoader对象作为该方法的参数传入。
如果把实现ResourceLoaderAware接口的Bean类部署在Spring容器中,Spring容器会将自身当成ResourceLoader作为setResourceLoader()方法的参数传入。由于ApplicationContext的实现类都实现了ResourceLoader接口,Spring容器自身完全可作为ResorceLoader使用。
创建一个类实现ResourceLoaderAware接口,并进行自动注入
@Component
public class TestBean implements ResourceLoaderAware {
@Autowired
private ResourceLoader resourceLoader;
@Override
public void setResourceLoader(ResourceLoader resourceLoader) {
this.resourceLoader=resourceLoader;
}
public ResourceLoader getResourceLoader() {
return this.resourceLoader;
}
}
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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--开启组件扫描功能-->
<context:component-scan base-package="com.atguigu.spring6.resourceloaderaware"></context:component-scan>
</beans>
测试类:
public class TestDemo {
public static void main(String[] args) {
ApplicationContext context =
new ClassPathXmlApplicationContext("bean.xml");
TestBean bean = context.getBean(TestBean.class);
ResourceLoader resourceLoader = bean.getResourceLoader();
System.out.println(context == resourceLoader); //测试bean容器是否为resourceloder
}
}
输出结果:
7.5、 使用Resource 作为属性
前面介绍了 Spring 提供的资源访问策略,但这些依赖访问策略要么需要使用 Resource 实现类,要么需要使用 ApplicationContext 来获取资源(注:如果资源改变了路径,那么使用该资源的代码需要重写该资源的路径,非常麻烦)。实际上,当应用程序中的 Bean 实例需要访问资源时,Spring 有更好的解决方法:直接利用依赖注入。从这个意义上来看,Spring 框架不仅充分利用了策略模式来简化资源访问,而且还将策略模式和 IoC 进行充分地结合,最大程度地简化了 Spring 资源访问。
归纳起来,如果 Bean 实例需要访问资源,有如下两种解决方案:
- 代码中获取 Resource 实例
- 使用依赖注入
对于第一种方式,当程序获取 Resource 实例时,总需要提供 Resource 所在的位置,不管通过 FileSystemResource 创建实例,还是通过 ClassPathResource 创建实例,或者通过 ApplicationContext 的 getResource() 方法获取实例,都需要提供资源位置。这意味着:资源所在的物理位置将被耦合到代码中,如果资源位置发生改变,则必须改写程序。因此,通常建议采用第二种方法,让 Spring 为 Bean 实例依赖注入资源。
创建类:
public class ResourceBean {
private Resource resource;
public Resource getResource() {
return resource;
}
public void setResource(Resource resource) {
this.resource = resource;
}
public void parse() {
System.out.println(resource.getFilename());
System.out.println(resource.getDescription());
}
}
配置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">
<bean id="resourceBean" class="com.atguigu.spring6.di.ResourceBean" >
<!-- 可以使用file:、http:、ftp:等前缀强制Spring采用对应的资源访问策略 -->
<!-- 如果不采用任何前缀,则Spring将采用与该ApplicationContext相同的资源访问策略来访问资源 -->
<property name="resource" value="classpath:test.txt"/>
</bean>
</beans>
创建测试类:
public class TestBean {
public static void main(String[] args) {
ApplicationContext context =
new ClassPathXmlApplicationContext("beans.xml");
ResourceBean bean = context.getBean(ResourceBean.class);
bean.parse();
}
}
测试结果:
7.6、 应用程序上下文和资源路径
7.6.1、 概述
不管以怎样的方式创建ApplicationContext实例,都需要为ApplicationContext指定配置文件,Spring允许使用一份或多分XML配置文件。当程序创建ApplicationContext实例时,通常也是以Resource的方式来访问配置文件的,所以ApplicationContext完全支持ClassPathResource、FileSystemResource、ServletContextResource等资源访问方式。
ApplicationContext确定资源访问策略通常有两种方法:
(1)使用ApplicationContext实现类指定访问策略。
(2)使用前缀指定访问策略。
7.6.2、 ApplicationContext实现类指定访问策略
创建ApplicationContext对象时,通常可以使用如下实现类:
(1) ClassPathXMLApplicationContext : 对应使用ClassPathResource进行资源访问。
(2)FileSystemXmlApplicationContext : 对应使用FileSystemResource进行资源访问。
(3)XmlWebApplicationContext : 对应使用ServletContextResource进行资源访问。
当使用ApplicationContext的不同实现类时,就意味着Spring使用相应的资源访问策略。
7.6.3、使用前缀指定访问策略
classpath前缀使用
public class TestDemo {
/*
* 通过搜索文件系统路径下的xml文件创建ApplicationContext,
* 但通过指定classpath:前缀强制搜索类加载路径
* classpath:bean.xml
* */
public static void main(String[] args) {
ApplicationContext context =
new ClassPathXmlApplicationContext("classpath:bean.xml");
Resource resource = context.getResource("test.txt");
System.out.println(resource.getDescription());
}
}
classpath通配符使用
classpath * :前缀提供了加载多个XML配置文件的能力,当使用classpath*:前缀来指定XML配置文件时,系统将搜索类加载路径,找到所有与文件名匹配的文件,分别加载文件中的配置定义,最后合并成一个ApplicationContext。
ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath*:bean.xml");
当使用classpath * :前缀时,Spring将会搜索类加载路径下所有满足该规则的配置文件。
如果不是采用classpath * :前缀,而是改为使用classpath:前缀,Spring则只加载第一个符合条件的XML文件
注意:classpath * : 前缀仅对ApplicationContext有效。实际情况是,创建ApplicationContext时,分别访问多个配置文件(通过ClassLoader的getResource方法实现)。因此,classpath * :前缀不可用于Resource。
通配符其他使用
一次性加载多个配置文件的方式:指定配置文件时使用通配符
//以bean开头的xml文件
ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:bean*.xml");
Spring允许将classpath*:前缀和通配符结合使用
ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath*:bean*.xml");
8、 国际化:i18n
8.1、 i18n概述
国际化也称作i18n,其来源是英文单词 internationalization的首末字符i和n,18为中间的字符数。由于软件发行可能面向多个国家,对于不同国家的用户,软件显示不同语言的过程就是国际化。通常来讲,软件中的国际化是通过配置文件来实现的,假设要支撑两种语言,那么就需要两个版本的配置文件。
8.2、 Java国际化
Java自身是支持国际化的,java.util.Locale用于指定当前用户所属的语言环境等信息,java.util.ResourceBundle用于查找绑定对应的资源文件。Locale包含了language信息和country信息,Locale创建默认locale对象时使用的静态方法。
配置文件命名规则:
basename_language_country.properties
必须遵循以上的命名规则,java才会识别。其中,basename是必须的,语言和国家是可选的。这里存在一个优先级概念,如果同时提供了messages.properties和messages_zh_CN.propertes两个配置文件,如果提供的locale符合en_CN,那么优先查找messages_en_CN.propertes配置文件,如果没查找到,再查找messages.properties配置文件。最后,提示下,所有的配置文件必须放在classpath中,一般放在resources目录下
public class ResourceI18n {
public static void main(String[] args) {
ResourceBundle bundle1 = ResourceBundle.getBundle("messages",
new Locale("zh", "CN"));
String test = bundle1.getString("test");
System.out.println(test);
ResourceBundle bundle2 = ResourceBundle.getBundle("messages",
new Locale("en", "GB"));
String test1 = bundle2.getString("test");
System.out.println(test1);
}
}
运行结果:
8.3、 Spring6国际化
8.3.1、 MessageSource接口
spring中国际化是通过MessageSource这个接口来支持的
常见实现类
ResourceBundleMessageSource
这个是基于Java的ResourceBundle基础类实现,允许仅通过资源名加载国际化资源
ReloadableResourceBundleMessageSource
这个功能和第一个类的功能类似,多了定时刷新功能,允许在不重启系统的情况下,更新资源的信息
StaticMessageSource
它允许通过编程的方式提供国际化信息,一会我们可以通过这个来实现db中存储国际化信息的功能。
8.3.2、 使用Spring6国际化
创建atguigu_en_GB.properties
www.atguigu.com=welcome {0},time:{1}
创建atguigu_zh_CN.properties
www.atguigu.com=欢迎 {0},时间:{1}
测试类:
public class ResourceI18n {
public static void main(String[] args) {
ApplicationContext context =
new ClassPathXmlApplicationContext("bean.xml");
//传递动态参数,使用数组形式对应{0} {1}顺序
Object[] objs = new Object[]{"atguigu", new Date().toString()};
//www.atguigu.com为资源文件的key值,
//objs为资源文件value值所需要的参数,Local.CHINA为国际化为语言
//测试英文将CHINA改为UK即可
String message = context.getMessage("www.atguigu.com", objs, Locale.UK);
System.out.println(message);
}
}
运行结果:
9、数据校验:Validation
在开发中,我们经常遇到参数校验的需求,比如用户注册的时候,要校验用户名不能为空、用户名长度不超过20个字符、手机号是合法的手机号格式等等。如果使用普通方式,我们会把校验的代码和真正的业务处理逻辑耦合在一起,而且如果未来要新增一种校验逻辑也需要在修改多个地方。而spring validation允许通过注解的方式来定义对象校验规则,把校验和业务逻辑分离开,让代码编写更加方便。Spring Validation其实就是对Hibernate Validator进一步的封装,方便在Spring中使用。
在Spring中有多种校验的方式
第一种是通过实现org.springframework.validation.Validator接口,然后在代码中调用这个类
第二种是按照Bean Validation方式来进行校验,即通过注解的方式。
第三种是基于方法实现校验
除此之外,还可以实现自定义校验
9.1、 通过Validator接口实现
引入相关依赖
<dependencies>
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>7.0.5.Final</version>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>jakarta.el</artifactId>
<version>4.0.1</version>
</dependency>
</dependencies>
创建一个Person类,并设置name,age属性,配置它们的set、get方法。
public class Person {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
创建类实现Validator接口,实现接口方法指定校验规则
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
public class PersonValidator implements Validator {
//对类型校验
@Override
public boolean supports(Class<?> clazz) {
return Person.class.equals(clazz);
}
//校验规则
@Override
public void validate(Object target, Errors errors) {
//name不能为空
ValidationUtils.rejectIfEmpty(errors,"name",
"name.empty","name is null");
//age 不能小于0 不能大于200
Person p = (Person)target;
if(p.getAge() < 0){
errors.rejectValue("age", "age.value.error",
"age.value < 0");
} else if (p.getAge() > 200) {
errors.rejectValue("age", "age.value.error.old",
"age.value > 200");
}
}
}
创建测试类并测试:
public class TestPerson {
public static void main(String[] args) {
//创建person对象
Person person = new Person();
person.setName("tony");
person.setAge(-1);
//创建person对象的data binder
DataBinder binder = new DataBinder(person);
//设置校验器
binder.setValidator(new PersonValidator());
//调用方法执行校验
binder.validate();
//输出校验结果
BindingResult result = binder.getBindingResult();
System.out.println(result.getAllErrors());
}
}
运行结果:
9.2、Bean Validation注解实现
使用Bean Validation校验方式,就是如何将Bean Validation需要使用的javax.validation.ValidatorFactory 和javax.validation.Validator注入到容器中。spring默认有一个实现类LocalValidatorFactoryBean,它实现了上面Bean Validation中的接口,并且也实现了org.springframework.validation.Validator接口。
常用注解说明
@NotNull 限制必须不为null
@NotEmpty 只作用于字符串类型,字符串不为空,并且长度不为0
@NotBlank 只作用于字符串类型,字符串不为空,并且trim()后不为空串
@DecimalMax(value) 限制必须为一个不大于指定值的数字
@DecimalMin(value) 限制必须为一个不小于指定值的数字
@Max(value) 限制必须为一个不大于指定值的数字
@Min(value) 限制必须为一个不小于指定值的数字
@Pattern(value) 限制必须符合指定的正则表达式
@Size(max,min) 限制字符长度必须在min到max之间
@Email 验证注解的元素值是Email,也可以通过正则表达式和flag指定自定义的email格式
创建配置类,配置LocalValidatorFactoryBean
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
@Configuration
@ComponentScan("com.atguigu.spring6.validator.two")
public class ValidationConfig {
@Bean
public LocalValidatorFactoryBean validator() {
return new LocalValidatorFactoryBean();
}
}
创建实体类,使用注解定义校验规则
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
public class User {
@NotNull
private String name;
@Min(0)
@Max(200)
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
使用jakarta.validation.Validator校验
import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Set;
@Service
public class MyValidation1 {
@Autowired
private Validator validator;
public boolean byUser(User user){
Set<ConstraintViolation<User>> validate = validator.validate(user);
return validate.isEmpty();
};
}
使用org.springframework.validation.Validator校验
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.validation.Validator;
import java.util.List;
@Service
public class MyValidation2 {
@Autowired
private Validator validator;
public boolean ByUsertwo(User user){
BindException bindException = new BindException(user, user.getName());
validator.validate(user,bindException);
List<ObjectError> allErrors = bindException.getAllErrors();
System.out.println(allErrors);
return bindException.hasErrors();
}
}
测试类:
public class TestUser {
@Test
public void testOne() {
ApplicationContext context =
new AnnotationConfigApplicationContext(ValidationConfig.class);
MyValidation1 validation1 = context.getBean(MyValidation1.class);
User user = new User();
user.setName("tom");
user.setAge(-1);
boolean message = validation1.byUser(user);
System.out.println(message);
}
@Test
public void testTwo() {
ApplicationContext context =
new AnnotationConfigApplicationContext(ValidationConfig.class);
MyValidation2 validation2 = context.getBean(MyValidation2.class);
User user = new User();
user.setName("tom");
user.setAge(-1);
boolean b = validation2.ByUsertwo(user);
System.out.println(b);
}
}
运行结果:
one:
two:
9.3、 基于方法实现校验
创建User类
public class User {
@NotNull
private String name;
@Min(0)
@Max(150)
private int age;
@Pattern(regexp = "^1(3|4|5|7|8)\\d{9}$",message = "手机号码格式错误")
@NotBlank(message = "手机号码不能为空")
private String phone;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
", phone='" + phone + '\'' +
'}';
}
}
创建配置类,配置MethodValidationPostProcessor
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.beanvalidation.MethodValidationPostProcessor;
@Configuration
@ComponentScan("com.atguigu.spring6.validator.three")
public class ValidationConfig {
@Bean
public MethodValidationPostProcessor validationPostProcessor() {
return new MethodValidationPostProcessor();
}
}
定义Service类,通过注解操作对象
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;
@Service
@Validated
public class MyService {
public String testMethod(@NotNull @Valid User user) {
return user.toString();
}
}
测试:
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class TestUser {
public static void main(String[] args) {
ApplicationContext context =
new AnnotationConfigApplicationContext(ValidationConfig.class);
MyService bean = context.getBean(MyService.class);
User user = new User();
user.setName("tom");
user.setAge(20);
user.setPhone("13333333333");
String s = bean.testMethod(user);
System.out.println(s);
}
}
运行结果:
9.4、 实现自定义校验
自定义校验注解
import jakarta.validation.Constraint;
import jakarta.validation.Payload;
import java.lang.annotation.*;
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(validatedBy = {CannotBlankValidator.class})
public @interface CannotBlank {
//默认错误消息
String message() default "不能包含空格";
//分组
Class<?>[] groups() default {};
//负载
Class<? extends Payload>[] payload() default {};
//指定多个时使用
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.TYPE_USE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@interface List {
CannotBlank[] value();
}
}
编写真正的校验类
public class CannotBlankValidator implements ConstraintValidator<CannotBlank, String> {
@Override
public void initialize(CannotBlank constraintAnnotation) {
}
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
//null时不进行校验
if (value != null && value.contains(" ")) {
//获取默认提示信息
String defaultConstraintMessageTemplate = context.getDefaultConstraintMessageTemplate();
System.out.println("default message :" + defaultConstraintMessageTemplate);
//禁用默认提示信息
context.disableDefaultConstraintViolation();
//设置提示语
context.buildConstraintViolationWithTemplate("can not contains blank").addConstraintViolation();
return false;
}
return true;
}
}
运行:
10、提前编译 AOT
略。。。