Spring学习笔记
建议配合目录使用
1.Spring简介
使现有的技术更加容易使用,本身是一个大杂烩,整合了现有的所有技术
SSH:Struct2 + Spring + Hibernate
SSM:SpringMVC + Spring + Mybatis
官方下载:https://repo.spring.io/ui/native/release/org/springframework/spring/
github地址:https://github.com/spring-projects/spring-framework
<!--maven-->
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.19</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.19</version>
</dependency>
优点:开源免费的容器,轻量级的非入侵式的框架,支持事务的处理,对框架整合的支持
两大特性:控制反转(IOC)、面向切面编程(AOP)
- Spring Boot:
- 一个快速开发的脚手架
- 基于SpringBoot可以快速开发单个微服务
- 约定大于配置
- Spring Cloud:
- SpringCloud是基于SpringBoot实现的
2.IOC理论
1.基本原理
原理说明
之前,程序是主动创建对象!控制权在程序手上;使用了set注入后,程序不再具有主动性,而是变成了被动的接受对象
//通过利用接口来达到用户决定
//通过多态将控制权交到用户手上,而不是写死在程序中
private UserDao userDao;
public void setUserDao(UserDao userDao){
this.userDao = userDao;
userDao.test();
}
控制反转(IOC)是一种设计思想,依赖注入(DI)是实现IOC的一种方法,也有人认为DI只是IOC的另一种说法。没有IOC的程序中,我们使用面向对象编程,对象的创建与对象间的依赖关系完全硬编码在程序中,对象的创建由程序自己控制,控制反转后将对象的创建转移给第三方,可以理解为:获得依赖对象的方式反转了。
采用XML方式配置Bean的时候,Bean的定义信息是和实现分离的,而采用注解的方式可以把两者合二为一,Bean的定义信息直接以注解的形式定义在实现类中,从而达到了零配置的目的。
控制反转是一种通过描述(XML或注解)并通过第三方去生产或获取特定对象的方式。在Spring中实现控制反转的是IOC容器,其方法是依赖注入(DI)。
本质上是将对象交给Spring托管,由Spring负责创建、管理、装配。也就是说修改需求只需要在配置文件中修改,不需要对代码做改动。
bean的调用
在bean中创建了对象之后,在java中就不再需要new对象了,直接通过getBean方法获得bean中创建的对象
import com.Gw.pojo.Student;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class test {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Student student = context.getBean("student", Student.class); //使用反射机制,避免强转
System.out.println(student.getName());
}
}
2.一些配置
- xml模板,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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="..." class="...">
<!-- collaborators and configuration for this bean go here -->
</bean>
<bean id="..." class="...">
<!-- collaborators and configuration for this bean go here -->
</bean>
<!-- more bean definitions go here -->
<import resource="beans1.xml"></import>
</beans>
- 别名,给bean取别名,可通过别名获取对象
<alias name="oldName" alias="newName"/>
- bean配置
<!--id为新建的对象名,class为对应的实体类,name可以起别名,同时可以取多个,property对应形参-->
<bean id="oldName" class="com.Gw.pojo.user" name="newName1 newName2,newName3...">
<property name="name" value="yGw"></property>
</bean>
- import
一般用于团队开发,将多个applicationContext.xml合并为一个applicationContext.xml
<import resource="beans1.xml"></import>
<import resource="beans2.xml"></import>
<import resource="beans3.xml"></import>
3.依赖注入
- 依赖:bean对象的创建依赖于容器!
- 注入:bean对象中的所有属性由容器来注入!
1.构造器注入
在配置文件加载的时候,容器中所有的对象都已经加载了(调用构造函数)
1.默认使用无参构造
2.如果要使用有参构造
- 下标赋值
<bean id="user" class="com.Gw.pojo.User">
<constructor-arg index="0" value="Gw"/>
</bean>
- 类型
<bean id="user" class="com.Gw.pojo.User">
<!--对于引用类型必须指明具体-->
<constructor-arg type="java.lang.String" value="Gw2"/>
</bean>
- 参数名
<bean id="user" class="com.Gw.pojo.User">
<constructor-arg name="name" value="Gw3"/>
</bean>
- bean注入
<bean id="BeanOne" class="x.y.thingOne">
<constructor-arg ref="BeanTwo"/>
<constructor-arg ref="BeanThree"/>
</bean>
<bean id="BeanTwo" class="x.y.thingTwo"/>
<bean id="BeanThree" class="x.y.thingThree"/>
2.Set方式注入
<!--常见的几种注入-->
<bean id="address" class="com.Gw.pojo.Address">
<property name="address" value="chengdu"></property>
</bean>
<bean id="student" class="com.Gw.pojo.Student">
<!--第一种value,普通注入-->
<property name="name" value="ygw"/>
<!--第二种ref,Bean注入-->
<property name="address" ref="address"/>
<!--第三种array,数组注入-->
<property name="books">
<array>
<value>红楼梦</value>
<value>西游记</value>
<value>水浒传</value>
<value>三国演义</value>
</array>
</property>
<!--list注入-->
<property name="hobbys">
<list>
<value>听歌</value>
<value>敲代码</value>
<value>打游戏</value>
<value>刷视频</value>
</list>
</property>
<!--map注入-->
<property name="card">
<map>
<entry key="卡1" value="123456"></entry>
<entry key="卡2" value="123456"></entry>
<entry key="卡3" value="123456"></entry>
</map>
</property>
<!--set注入-->
<property name="games">
<set>
<value>Naraka</value>
<value>ReadyOrNot</value>
<value>CS:GO</value>
</set>
</property>
<!--null注入-->
<property name="wife">
<null/>
</property>
<!--properties注入-->
<property name="info">
<props>
<prop key="学号">202013160322</prop>
<prop key="性别">男</prop>
<prop key="姓名">ygw</prop>
</props>
</property>
</bean>
3.拓展方式注入
p命名空间注入,直接将属性写在标签中,可看作set注入
<bean id="user" class="com.Gw.pojo.User" p:name="ygw" p:age="20"/>
在使用前需要加入约束
xmlns:p="http://www.springframework.org/schema/p"
c命名空间注入, 可以看作构造器注入
<bean id="user2" class="com.Gw.pojo.User" c:name="smart" c:age="21"/>
使用前加入约束
xmlns:p="http://www.springframework.org/schema/p"
4.Bean的作用域
- 单例模式(Spring默认),对于某个特定的bean,只生成一次对象,多次调用仍为相同的bean对象
<!--将scope设置为singleton,调用多次时不重复生成对象-->
<bean id="accountService" class="com.something.DefaultAccountService" scope="singleton"/>
- 原型模式,对于某个特定的bean,每次调用都重新生成一个新的对象
<!--将scope设置为prototype,调用时重新生成对象-->
<bean id="accountService" class="com.something.DefaultAccountService" scope="prototype"/>
其他的request、session、application、websocket在web中应用
4.Bean的自动装配
自动装配:自动的获取bean中引用型(ref)的属性值,byName和byType局限性都较大
- byName
<!--byName使用时需要保证所有bean的id唯一,并且这个bean需要和自动注入的属性的set方法的值一致-->
<bean id = "cat" class = "com.Gw.pojo.Cat"/>
<bean id = "dog" class = "com.Gw.pojo.Dog"/>
<bean id = "people" class = "com.Gw.pojo.people" autowire = "byName">
<property name = "name" value = "ygw"/>
<!--<property name = "dog" ref = "dog"/>-->
<!--<property name = "cat" ref = "cat"/>-->
</bean>
- byType
<!--byType使用时需要保证所有bean的class唯一,并且这个bean需要和自动注入的属性的set方法的值一致-->
<!--id可省略-->
<bean class = "com.Gw.pojo.Cat"/>
<bean class = "com.Gw.pojo.Dog"/>
<bean id = "people" class = "com.Gw.pojo.people" autowire = "byName">
<property name = "name" value = "ygw"/>
</bean>
1.注解实现自动装配
注解注入在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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.Gw"/>
<context:annotation-config/>
</beans>
2.@Autowired与@Resource
1.联系
- @Autowired和@Resource注解都是作为bean对象注入的时候使用的
- 两者都可以声明在字段和setter方法上
注意:如果声明在字段上,那么就不需要再写setter方法。但是本质上,该对象还是作为set方法的实参,通过执行set方法注入,只是省略了setter方法罢了
2.区别
- @Autowired注解是Spring提供的,而@Resource注解是J2EE本身提供的
- @Autowired注解默认通过byType方式注入,而@Resource注解默认通过byName方式注入,如无法匹配则使用byType实现
- @Autowired注解注入的对象需要在IOC容器中存在,否则需要加上属性required=false,表示忽略当前要注入的bean,如果有直接注入,没有跳过,不会报错
3.使用
- @Autowired默认的注入方式为byType,也就是根据类型匹配,当有多个实现时,则通过byName注入
- 可以通过配合@Qualifier注解来显式指定name值@Qualifier(name= "cat1"),指明要使用哪个具体的实现类,来解决byName名字和byType类型自动装配不匹配的问题
- 如果需要设置对象为空可以用注解@nullable或者@Autowired(required = false)
public class People {
@Autowired
@Qualifier(name="cat1")
private Cat cat;
@Autowired
@nullable //该字段可以为null 同样的作用也可以写成@Autowired(required = false)
private Dog dog;
String name;
public Cat getCat() {
return cat;
}
public Dog getDog() {
return dog;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
- @Resource首先通过byName匹配,当无法匹配IOC容器中任何一个id,于是通过byType匹配,如果类型的实现类有两个,仍然无法确定,于是报错。同时@Resource还有两个重要的属性:name和type,用来显式指定byName和byType方式注入;当指定某种方式匹配时,如果匹配不到则直接报错
@Resource(name=""/type="")
private Dog dog;
5.使用注解开发
说明:在Spring4之后使用注解必须要aop包,xml更加万能,维护更加方便;最好是xml用来管理bean,注解只负责属性的注入
使用注解前需要加入:
<!--包中填写需要扫描的内容-->
<context:component-scan base-package="com.Gw"/>
<context:annotation-config/>
@Component的衍生注解,@Component可以看做<bean id="" class=""~>,说明该类已被spring托管了,相同功能的注解还有以下几种
- @Repository -- Dao层
- @Service -- Service层
- @Controller -- Controller层
@Value可以看做<property><value></value~> </property~>,通过value直接注入
@Scope用来设置作用域@Scope("singleton/prototype/....")
@Component
public class User {
@Value("ygw")
private String name;
public String getName() {
return name;
}
}
6.使用Java方式配置Spring
//Configuration本质上就是Component,@Configuration可以等价于applicationContext.xml
//使用了configuration就说明这是一个配置文件,配置类
@Configuration //相当于xml配置中的annotation-config,开启注解
@ConponentScan("com.Gw.pojo") //扫描包相当于xml配置中的conponent-scan,使用注解的范围
@Import("Myconfig2.class") //引入其他包
public class Myconfig {
//等价于<bean id = "getUser" class = "com.Gw.pojo.User"/>
@Bean //相当于在xml中注册的bean,可与@Component转化
@Value("ygw")
public User getUser(){
return new User();
}
}
//如果完全使用了配置类去做,则配置的使用通过AnnotationConfigApplicationContext获取上下文
@Test
public void test1(){
ApplicationContext context = new AnnotationConfigApplicationContext(Myconfig.class);
User user = context.getBean("getUser", User.class);
System.out.println(user.getName());
}
7.动态代理
动态代理主要会用到Proxy和InvocationHandler,前者用于通过代理实现代理对象实例的生成,后者的invoke方法则用于扩展原有的方法
- InvocationHandler(动态代理)
//InvocationHandler是一个接口,定义了invoke方法,invoke是生成proxy实例的方法
Object invoke(Object proxy, Method method, Object[] args) throws Throwable;
- Proxy(代理人)
Modifier and Type | Method and Description |
---|---|
static InvocationHandler |
getInvocationHandler(Object proxy) Returns the invocation handler for the specified proxy instance. |
static Class<?> |
getProxyClass(ClassLoader loader, Class<?>... interfaces) Returns the java.lang.Class object for a proxy class given a class loader and an array of interfaces. |
static boolean |
isProxyClass(Class<?> cl) Returns true if and only if the specified class was dynamically generated to be a proxy class using the getProxyClass method or the newProxyInstance method. |
static Object |
newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h) Returns an instance of a proxy class for the specified interfaces that dispatches method invocations to the specified invocation handler. |
举例说明,在原有业务UserService的基础上加上日志输出
package com.Gw.demo01;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
//动态代理的实现
public class ProxyInvocationHandler implements InvocationHandler {
private Object target;
public void setTarget(Object target) {
this.target = target;
}
public Object getProxy(){
return Proxy.newProxyInstance(target.getClass().getClassLoader(),target.getClass().getInterfaces(),this);
}
//最最最最重要的方法,在使用getProxy()方法时,给出的InvocationHandler是this,也就是说代理人在动态的执行userService中的方法时会调用当前类的invoke方法,在这个方法中用method.invoke()来调用代理对象的方法
@Override
public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
log(method.getName());
Object result = method.invoke(target, objects);
return result;
}
public void log(String msg){
System.out.println("[debug] 执行了" + msg +"方法");
}
}
import com.Gw.demo01.ProxyInvocationHandler;
import com.Gw.demo01.UserService;
import com.Gw.demo01.UserServiceImpl;
//使用动态代理
public class test {
public static void main(String[] args) {
//先new出需要代理的对象userService
UserServiceImpl userService = new UserServiceImpl();
//将userService放入动态代理器中,并获取代理人proxy
ProxyInvocationHandler proxyInvocationHandler = new ProxyInvocationHandler();
proxyInvocationHandler.setTarget(userService);
UserService proxy = (UserService) proxyInvocationHandler.getProxy();
//通过代理人进行操作
proxy.delete();
proxy.add();
}
}
8.AOP
提供声明式事务;允许用户自定义切面
使用Spring-AOP需要导入依赖
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.9.1</version>
<scope>runtime</scope>
</dependency>
1.一些术语的说明
- 横切关注点:跨越应用程序的多个模块的方法或功能,与业务逻辑无关,但需要关注的部分,如:日志、安全、缓存、事务等等
- 切面(aspect):横切关注点被模块化的特殊对象,如log类
- 通知(advice):切面必须要完成的工作,也就是log类中的一个方法
- 目标(target):被通知的对象
- 代理(proxy):向目标对象应用通知后创建的对象
- 切入点(pointCut):切面通知执行的地点
- 连接点(joinPoint):与切入点匹配的执行点
2.Spring中AOP的三种实现方法
方法一:使用Spring中的API
public class log implements MethodBeforeAdvice {
//method:要执行的方法
//args:参数
//target:目标对象
@Override
public void before(Method method, Object[] args, Object target) throws Throwable {
System.out.println(target.getClass().getName() + "的" +method.getName() + "方法被执行了");
}
}
public class afterLog implements AfterReturningAdvice {
//returnValue:返回值
@Override
public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
System.out.println("方法"+method.getName()+"的执行结果为"+returnValue);
}
}
在xml中的配置
<!--方法一:未自定义切面-->
<bean id = "userService" class = "com.GW.service.userService"/>
<bean id = "beforeLog" class = "com.GW.log.beforeLog"/>
<bean id = "afterLog" class = "com.GW.log.afterLog"/>
<!--配置AOP,需要导入AOP的约束-->
<!--此处本质上是相当于动态代理对InvocationHandler接口的实现,即对原有业务进行拓展,将通知advice放入bean中,再将通知织入,此处类似于invoke方法中对添加方法织入的实现-->
<aop:config>
<!--定义一个切入点,execution写切入点位置,*代表任意位置-->
<aop:pointcut id="pointcut" expression="execution(* com.Gw.demo01.UserServiceImpl.*(..))"/>
<aop:advisor advice-ref="beforeLog" pointcut-ref="pointcut"/>
<aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
</aop:config>
调用的主程序
package com.Gw.Log;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Mytest {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext();
//注意!!此处是接口,动态代理的代理后的对象要给接口
userService userService = context.getBean("userService", userService.class);
userService.add(); //本质上是代理对象对invoke方法的调用,通过aop将log进行织入
}
}
方法二:自定义切面
将要织入的方法放在一个类中,在aop的配置中,通过设置切面,在切面中设置切入点,通过通知环绕(aop:before 或aop:after)将方法织入
public class diyAspect {
public void before(){
System.out.println("=========before=========");
}
public void after(){
System.out.println("=========after==========");
}
}
在xml中的配置
<!--方法二:自定义切面-->
<bean id="diyaspect" class="com.Gw.diy.diyAspect"/>
<aop:config>
<!--自定义切面-->
<aop:aspect ref="diyaspect">
<!--设置切入点-->
<aop:pointcut id="point" expression="execution(* com.Gw.demo01.UserServiceImpl.*(..))"/>
<!--通知,可直接调用切面中的方法-->
<aop:before method="before" pointcut-ref="point"/>
<aop:after method="after" pointcut-ref="point"/>
</aop:aspect>
</aop:config>
方法三:使用注解实现
非常的方便!!!
注意:在applicationContext.xml中需要开启注解支持,并且对于没有使用@Component注解的类需要注册bean
<!--需要添加aop的头文件-->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--开启注解支持-->
<aop:aspectj-autoproxy/>
</beans>
使用注解示例
package com.Gw;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
@Aspect //设置切面
public class Annotation {
//设置切入点和通知
@Before("execution(* com.Gw.demo01.UserServiceImpl.*(..))")
public void before(){
System.out.println("=========before=========");
}
@After("execution(* com.Gw.demo01.UserServiceImpl.*(..))")
public void after(){
System.out.println("=========after==========");
}
@Around("execution(* com.Gw.demo01.UserServiceImpl.*(..))")
public void around(ProceedingJoinPoint jp) throws Throwable {
System.out.println("环绕前");
Object proceed = jp.proceed();
System.out.println("环绕后");
}
}
执行顺序:
9.整合Mybatis
关于mybatis-spring依赖的使用
用spring的配置取代mybatis-config.xml的配置,通常只在mybatis-config.xml中配置别名管理和设置
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--做别名管理和设置-->
<typeAliases>
<package name="com.Gw.pojo"/>
</typeAliases>
</configuration>
导入的依赖:
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.29</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.19</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.19</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.9.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.7</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.22</version>
<scope>compile</scope>
</dependency>
</dependencies>
方法一:直接实现
文件结构
总的来说,在spring-dao.xml中是替代了原先的mybatis-config.xml,利用spring带有的类来实现sqlSession的创建,spring-dao.xml中专注于与数据库做连接,而一些其他的需要spring托管的类放在applicationContext.xml中
在spring-dao.xml中,sqlSession需要通过SqlSessionTemplate类创建;而SqlSessionTemplate在使用时又需要SqlSessionFactory,并通过构造函数注入的方法注入;SqlSessionFactory则指定了数据源、mybatis配置、mapper的注册;数据源中包括了与数据库连接的基本信息,通过DriverManagerDataSource类创建
spring-dao.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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!--代替了mybatis中的dataSource的配置-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
<!--url在idea连接数据库时查看-->
<property name="url" value="jdbc:mysql://localhost:3306"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</bean>
<!--代替了创建sqlSessionFactory的部分,可在配置Bean文件中直接通过ref使用-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--绑定mybatis的数据源-->
<property name="dataSource" ref="dataSource" />
<!--绑定mybatis的配置,在mybatis-config中进行一些mybatis的配置(虽然spring也可直接配置)-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<!--将mapper.xml注册-->
<property name="mapperLocations" value="classpath:com/Gw/mapper/*.xml"/>
</bean>
<!--通过使用SqlSessionTemplate完成了SqlSession对象的创建,SqlSessionTemplate需要SqlSessionFactory这个参数-->
<!--需要的这个参数没有其他的注入方式,只能通过构造器注入-->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
</beans>
在UserMapperImpl中实现通过mybatis与数据库做连接,在使用时直接调用UserMapperImpl类,不再需要专门通过sqlSession做连接。UserMapperImpl实际上起到的作用是封装后交由spring托管,调用时不再显示mybatis的实现细节
UserMapperImpl.java
package com.Gw.Mapper;
import com.Gw.pojo.User;
import org.mybatis.spring.SqlSessionTemplate;
import java.util.List;
public class UserMapperImpl implements UserMapper {
//我们所有的操作现在都使用SqlSessionTemplate来执行
private SqlSessionTemplate sqlSession;
//该类交由spring托管后通过set方式注入sqlSession
public void setSqlSession(SqlSessionTemplate sqlSession) {
this.sqlSession = sqlSession;
}
@Override
public List<User> selectUser() {
return sqlSession.getMapper(UserMapper.class).selectUser();
}
}
最后将UserMapperImpl在applicationContext.xml交由spring托管
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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<import resource="spring-dao.xml"/>
<!--将UserMapperImpl类交由spring托管-->
<bean id="userMapper" class="com.Gw.mapper.UserMapperImpl">
<!--将sqlSession通过set方式注入-->
<property name="sqlSession" ref="sqlSession"/>
</bean>
</beans>
方法二:SqlSessionDaoSupport简便实现
在一的配置的基础上继承SqlSessionDaoSupport,省去了创建sqlSession对象的麻烦,sqlSession对象直接由getSession()方法获得,对应的mapper实现类如下:
UserMapperImpl2.java
package com.Gw.Mapper;
import com.Gw.pojo.User;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import java.util.List;
public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper{
//直接通过getSqlSession()获得对象,继承SqlSessionDaoSupport
@Override
public List<User> selectUser() {
SqlSession sqlSession = getSqlSession();
return sqlSession.getMapper(UserMapper.class).selectUser();
}
}
将该类交由spring托管
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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<import resource="spring-dao.xml"/>
<!--将UserMapperImpl2类交由spring托管-->
<bean id="userMapper" class="com.Gw.mapper.UserMapperImpl">
<!--使用DaoSupport仅需要注入sqlSessionFactory即可-->
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
</beans>
10.声明式事务
事务的管理有声明式事务和编程式事务,前者用aop实现,后者用trycatch实现
把一组业务当做一个业务来开发,要么都成功,要么都失败,确保完整性和一致性,spring 保证的是在不改变原有代码的基础上进行事务注入,非常的nice
事务的ACID原则:
原子性、一致性、隔离性、持久性
添加配置tx
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/context/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-aop.xsd">
要开启spring 的事务管理功能需要在spring的配置文件中创建一个DataSourceTransactionManager对象
<!--要开启 Spring 的事务处理功能,在 Spring 的配置文件中创建一个 DataSourceTransactionManager 对象-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<constructor-arg ref="dataSource" />
</bean>
<!--结合AOP实现事务的织入-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<!--给哪些方法配置事务-->
<!--配置事务的七种传播特性,通常为required-->
<tx:attributes>
<tx:method name="selectUser" read-only="true"/>
<tx:method name="add" propagation="REQUIRED"/>
<tx:method name="delete"/>
<tx:method name="update"/>
<tx:method name="*"/>
</tx:attributes>
</tx:advice>
<!--配置事务切入点-->
<aop:config>
<aop:pointcut id="txPointcut" expression="execution(* com.Gw.Mapper.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
</aop:config>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现