Spring
1、简介
Spring是一个开源框架,它由[Rod Johnson](https://baike.baidu.com/item/Rod Johnson)创建。它是为了解决企业应用开发的复杂性而创建的。Spring使用基本的JavaBean来完成以前只可能由EJB完成的事情。然而,Spring的用途不仅限于服务器端的开发。从简单性、可测试性和松耦合的角度而言,任何Java应用都可以从Spring中受益。
Spring是一个轻量级的**控制反转(IoC)和面向切面(AOP)**的容器框架。
简化企业级开发的复杂度
框架构成
在学习Spring+SpringMvc的基础上,才能够学习SpringBoot,
2、IOC(控制反转)
Dao层
Service层
通过程序决定常见那个对象,写死了,用户需求不同就需要修改代码以实现不同的功能,控制权在程序哪里
加入了IOC后,使用Set注入,用户自主选择功能,不再需要修改代码,程序被动的接收对象,控制权交给了用户
就类似于把选择权交给用户,通过不同的输入,执行不同的代码,简化了程序代码,降低了系统的耦合性,
控制反转:获得依赖对象的方式反转了
3、IOC创建对象
无参构造
<?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="user" class="com.liu.pojo.User"> <!-- == new User()-->
<property name="name" value="lzw"/> <!--设置name值为lzw-->
</bean>
</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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="user" class="com.liu.pojo.User">
<!--通过constructor标签来对有参构造函数 注入参数,index为参数下标-->
<constructor-arg index="0" value="lzw"/>
</bean>
</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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--只要这个文件被加载,这里面定义的所有对象都会被实例化-->
<!--通过类型,对属性赋值,引用类型比较特殊,常用类型如int,可以直接int,
但是String必须要要写Java.lang.String-->
<bean id="user" class="com.liu.pojo.User">
<constructor-arg type="java.lang.String" value="lzw"/>
</bean>
<bean id="user2" class="com.liu.pojo.User2">
</bean>
</beans>
通过属性名赋值
Rusult
4、Spring配置(XML)
4.1 Alias 别名
给bean标签取一个别名,getBean时调用别名也可以
4.2 Bean(实例化对象)、
4.3Import
用于团队开发使用,可以将多个配置文件导入合并为一个
5、依赖注入(dependency injection,DI)
5.1、构造器注入
5.2、Set方式注入
- 依赖:bean对象的创建依赖于容器
- 注入:bean对象的所有属性,由容器来赋值
<?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="address" class="com.liu.pojo.Address">
<property name="address" value="Yaan"/>
</bean>
<bean id="student" class="com.liu.pojo.Student">
<!--1、普通值注入-->
<property name="name" value="lzw"/>
<!--2、Bean注入-->
<property name="address" ref="address"/>
<!--3、数组注入-->
<property name="books">
<array>
<value>红楼梦</value>
<value>西游记</value>
<value>水浒传</value>
<value>三国演义</value>
</array>
</property>
<!--4、List-->
<property name="hobbys">
<list>
<value>打球</value>
<value>看电影</value>
<value>奥里给</value>
</list>
</property>
<!--5、Map-->
<property name="card">
<map>
<entry key="学号" value="1"/>
<entry key="年龄" value="2"/>
<entry key="余额" value="3"/>
</map>
</property>
<!--6、Set-->
<property name="active">
<set>
<value>吃饭</value>
<value>睡觉</value>
<value>打豆豆</value>
</set>
</property>
<!--Null-->
<property name="wife">
<null/>
</property>
<!--Properties-->
<property name="info">
<props>
<prop key="lzw">刘正伟</prop>
<prop key="jss">姜胜森</prop>
<prop key="hyl">胡亚莉</prop>
</props>
</property>
</bean>
</beans>
import com.liu.pojo.Student;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* @version 1.0
* @description:TODO
* @Author:
* @date :2021/10/29 16:11
*/
public class Test {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Student sutdnet = (Student) context.getBean("student");
System.out.println(sutdnet.toString());
}
}
result
Student{name=‘lzw’, address=Yaan, books=[红楼梦, 西游记, 水浒传, 三国演义], hobbys=[打球, 看电影, 奥里给], card={学号=1, 年龄=2, 余额=3}, active=[吃饭, 睡觉, 打豆豆], wife=‘null’, info={lzw=刘正伟, hyl=胡亚莉, jss=姜胜森}}
5.3 、P命名空间&C命名空间注入
p命名空间注入
c命名空间注入
使用xml约束
xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
5.4、Bean Scope
-
单例模式 (Spring默认)
<bean id="hello" class="com.liu.pojo.Hello" scope="singleton">
getMapper(mappername),只要mappername一样,就只会创建一个实例
-
原型模式
<bean id="hello" class="com.liu.pojo.Hello" scope="prototype">
每次getMapper都会产生一个新的实例
-
request、session、application(只能在web开放中使用到)
6、Bean自动装配
- 自动装配时Spring满足Bean依赖的一种方式
- Spring会在上下文中自动寻找,并给Bean自动装配
6.1、ByName
当一个bean节点带有 autowire byName的属性时,将查找其类中所有的set方法名,获得将set去掉并且首字母小写的字符串,然后去spring容器中寻找是否有此字符串名称id的对象。如果有,就取出注入;如果没有,就报空指针异常。
6.2、ByType
该模式表示根据Property的数据类型(Type)自动装配,Spring会总动寻找与属性类型相同的bean,若一个bean的数据类型,兼容另一个bean中Property的数据类型,则自动装配。
即使id名字与set方法名字不一样也可以匹配
总结
byname的时候,需要保证所有bean的id唯一,并且这个bean需要和自动注入的属性的set方法的值一致
bytype的时候,需要保证所有bean的class唯一,并且这个bean需要和自动注入的属性的类型一致
6.3、注解实现自动装配
导入context约束、注解支持配置
<?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:annotation-config/>
</beans>
@Autowired
直接在属性上使用即可!也可以在set方式上使用
使用Autowired我们可以不用编写Set方法了,前提是你这个自动装配的属性在oc (spring)容器存在且符合名字byType,byName
@Autowired(required = false)说明这个对象可以为Null,否则不允许为空
7、Spring注解开发
package com.liu.pojo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* @version 1.0
* @description:TODO
* @Author:
* @date :2021/10/31 15:37
*/
//@Component 放在类上,说明这个类被Spring管理了,就是Bean
@Component //等价于 <bean id="user" class="com.liu.pojo.User"/>
public class User {
@Value("胡亚莉") //给属性注入
private String name;
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
'}';
}
}
衍生注解
@Component 由几个衍生的注解名,分别对应MVC三层架构
DAO @Repository
Service @Service
Controller @Controller
@Component @Repository @Service @Controller
这四个注解都是将类注册到Spring中, 装配Bean
作用域 @Scope
package com.liu.pojo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
/**
* @version 1.0
* @description:TODO
* @Author:
* @date :2021/10/31 15:37
*/
//@Component 放在类上,说明这个类被Spring管理了,就是Bean
@Component //等价于 <bean id="user" class="com.liu.pojo.User"/>
@Scope("singleton") //等价于 <bean id="user" class="com.liu.pojo.User" scope=”singleton“/>
public class User {
@Value("胡亚莉") //给属性注入,也可以放在对应的Set方法上,等价于 <property name=”name“ value=”胡亚莉“>
private String name;
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
'}';
}
}
小结:
XML与注解
- xml功能更加万能,适用于任何常见,维护简单
- 注解,不是自己类,是用不了,维护复杂
- xml负责管理Bean,注解负责完成属性注入
8、使用java配置Spring
完全脱离xml,全权交给java
Dao
package com.liu.pojo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* @version 1.0
* @description:TODO
* @Author:
* @date :2021/10/31 16:09
*/
@Component //@Conponent 放在类上,说明这个类被Spring管理了,就是Bean
public class User {
//等同于 <property name="name" value="刘正伟"/>
// @value可以写在属性上,也可以卸载44写在Set方法上,卸载属性上,可以省略不写Set方法
@Value("刘正伟")
private String name;
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
'}';
}
public String getName() {
return name;
}
}
Config
package com.liu.config;
import com.liu.pojo.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
/**
* @version 1.0
* @description:TODO
* @Author:
* @date :2021/10/31 16:10
*/
@Configuration //设置为配置文件
@ComponentScan("com.liu.pojo") //扫描包
public class JavaConfig {
// 注册一个bean,就相当于我们之前写的一个bean标签
// 这个方法的名字,就相当于bean标签中id属性
// 这个方法的返回值,就相当于bean标签中的class属性
@Bean
public User getUser(){
return new User();
}
}
Test
import com.liu.config.JavaConfig;
import com.liu.pojo.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
/**
* @version 1.0
* @description:TODO
* @Author:
* @date :2021/10/31 16:25
*/
public class test {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(JavaConfig.class);
User getUser = (User) context.getBean("getUser");
System.out.println(getUser.getName());
}
}
9、代理模式
SpringAOP的底层
9.1静态代理
Rent
package com.liu.Demo01;
public interface Rent {
public void rent();
}
Host
package com.liu.Demo01;
/**
* @version 1.0
* @description:TODO
* @Author:
* @date :2021/11/1 10:39
*/
public class Host implements Rent{
@Override
public void rent() {
System.out.println("我要出租房屋!");
}
}
Proxy
package com.liu.Demo01;
/**
* @version 1.0
* @description:TODO
* @Author:
* @date :2021/11/1 10:41
*/
//中介代理
public class proxy implements Rent {
private Host host; //组合方式将Host放入类
public proxy(Host host) {
this.host = host;
}
public proxy(){};
@Override
public void rent() {
System.out.println("===========================");
System.out.println("proxy.rent");
host.rent();
}
}
Consumer
package com.liu.Demo01;
/**
* @version 1.0
* @description:TODO
* @Author:
* @date :2021/11/1 10:40
*/
public class consumer {
public static void main(String[] args) {
Host host = new Host(); //建立一个真实角色,只负责自己的事(租房),不用管 其他的事交给代理绝取完成
proxy proxy = new proxy(host); //建一个代理角色,代理真是角色,
proxy.rent(); //通过代理角色租房,实现不接触房东完成租房
}
}
9、2动态代理
Rent
package com.liu.Demo03;
public interface Rent {
public void rent();
}
Host
package com.liu.Demo03;
public class Host implements Rent {
@Override
public void rent() {
System.out.println("我要出租房屋!");
}
}
InvocationHandler
package com.liu.Demo03;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
//用这个类生成代理类
public class InvocationHandler implements java.lang.reflect.InvocationHandler {
private Rent rent;
public void setRent(Rent rent) {
this.rent = rent;
}
//生成代理类
public Object getProxy() {
return Proxy.newProxyInstance(this.getClass().getClassLoader(),
rent.getClass().getInterfaces(), this);
}
//处理代理类,实例化代理类,并返回实例对象(Object)
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("=======================");
Object object = method.invoke(rent, args);
System.out.println("=======================");
return object;
}
}
Client
package com.liu.Demo03;
/**
* @version 1.0
* @description:TODO
* @Author:
* @date :2021/11/1 22:20
*/
public class Client {
public static void main(String[] args) {
Host host = new Host(); //创建真实对象
InvocationHandler invo = new InvocationHandler(); //获得代理类
invo.setRent(host); //给属性赋值
Rent proxy = (Rent)invo.getProxy(); //获得代理类实例化对象,注意这里是实例化 强转为 ==接口==
proxy.rent();
}
}
动态代理的好处:
- 可以使真实角色的操作更加纯粹!不用去关注一些公共的业务
- 公共角色就交给代理角色!实现了业务的分工!
- 公共业务发生扩展的时候,方便集中管理!
- 一个动态代理类代理的是一个接口,一般就是对应的一类业务
- 一个动态代理类可以代理多个类,只要是实现了同一个接口即可!
10、AOP
需要导入依赖
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.8.RC1</version>
<scope>runtime</scope>
</dependency>
方式一,java原生接口实现
User
package com.liu.service;
/**
* @version 1.0
* @description:TODO
* @Author:
* @date :2021/11/2 16:56
*/
public interface User {
public void add();
public void delete();
public void update();
public void query();
}
userServiceImpl
package com.liu.service;
/**
* @version 1.0
* @description:TODO
* @Author:
* @date :2021/11/2 16:57
*/
public class userServiceImpl implements User {
@Override
public void add() {
System.out.println("userServiceImpl.add");
}
@Override
public void delete() {
System.out.println("userServiceImpl.delete");
}
@Override
public void update() {
System.out.println("userServiceImpl.update");
}
@Override
public void query() {
System.out.println("userServiceImpl.query");
}
}
beforeLog
package com.liu.Log;
import org.springframework.aop.MethodBeforeAdvice;
import java.lang.reflect.Method;
/**
* @version 1.0
* @description:TODO
* @Author:
* @date :2021/11/2 16:59
*/
public class Beforelog implements MethodBeforeAdvice {
@Override
public void before(Method method, Object[] args, Object target) throws Throwable {
System.out.println(target.getClass().getName()+"的"+method.getName()+"()方法被执行了!");
}
}
AfterLog
package com.liu.Log;
import org.springframework.aop.AfterAdvice;
import org.springframework.aop.AfterReturningAdvice;
import java.lang.reflect.Method;
/**
* @version 1.0
* @description:TODO
* @Author:
* @date :2021/11/2 16:59
*/
public class Afterlog implements AfterReturningAdvice{
@Override
public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
System.out.println("执行了"+method.getName()+"返回了"+returnValue);
}
}
sping配置文件
<?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: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/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<bean id="userServiceImpl" class="com.liu.service.userServiceImpl"/>
<bean id="before" class="com.liu.Log.Beforelog"/>
<bean id="after" class="com.liu.Log.Afterlog"/>
<!--配置AOP:导入aop约束 -->
<aop:config>
<!--新增一个切入点(Catpoint) execution(要执行的位置!* * * *)-->
<aop:pointcut id="pointcut" expression="execution(* com.liu.service.userServiceImpl.*(..))"/>
<!--执行环绕增加-->
<aop:advisor advice-ref="before" pointcut-ref="pointcut"/> <!--在切入点执行before这个Bean>-->
<aop:advisor advice-ref="after" pointcut-ref="pointcut"/> <!--在切入点执行after这个Bean>-->
</aop:config>
</beans>
方式二,使用spring实现
Diy
package com.liu.DIy;
/**
* @version 1.0
* @description:TODO
* @Author:
* @date :2021/11/2 17:42
*/
public class diypc {
public void before() {
System.out.println("diypc.before");
}
public void after() {
System.out.println("diypc.after");
}
}
User
package com.liu.service;
/**
* @version 1.0
* @description:TODO
* @Author:
* @date :2021/11/2 16:56
*/
public interface User {
public void add();
public void delete();
public void update();
public void query();
}
userServiceImpl
package com.liu.service;
/**
* @version 1.0
* @description:TODO
* @Author:
* @date :2021/11/2 16:57
*/
public class userServiceImpl implements User {
@Override
public void add() {
System.out.println("userServiceImpl.add");
}
@Override
public void delete() {
System.out.println("userServiceImpl.delete");
}
@Override
public void update() {
System.out.println("userServiceImpl.update");
}
@Override
public void query() {
System.out.println("userServiceImpl.query");
}
}
beforeLog
package com.liu.Log;
import org.springframework.aop.MethodBeforeAdvice;
import java.lang.reflect.Method;
/**
* @version 1.0
* @description:TODO
* @Author:
* @date :2021/11/2 16:59
*/
public class Beforelog implements MethodBeforeAdvice {
@Override
public void before(Method method, Object[] args, Object target) throws Throwable {
System.out.println(target.getClass().getName()+"的"+method.getName()+"()方法被执行了!");
}
}
AfterLog
package com.liu.Log;
import org.springframework.aop.AfterAdvice;
import org.springframework.aop.AfterReturningAdvice;
import java.lang.reflect.Method;
/**
* @version 1.0
* @description:TODO
* @Author:
* @date :2021/11/2 16:59
*/
public class Afterlog implements AfterReturningAdvice{
@Override
public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
System.out.println("执行了"+method.getName()+"返回了"+returnValue);
}
}
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"
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/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<bean id="userServiceImpl" class="com.liu.service.userServiceImpl"/>
<bean id="before" class="com.liu.Log.Beforelog"/>
<bean id="after" class="com.liu.Log.Afterlog"/>
<bean id="diypc" class="com.liu.DIy.diypc"/>
<aop:config>
<!--自定义切面:ref要引用到类-->
<aop:aspect ref="diypc">
<!--切入点-->
<aop:pointcut id="pointcut" expression="execution(* com.liu.service.userServiceImpl.*(..))"/>
<!--通知-->
<aop:before method="before" pointcut-ref="pointcut"/> <!--在切入点之前执行 diypc Bean的before方法-->
<aop:after method="after" pointcut-ref="pointcut"/><!--在切入点之后执行 diypc Bean的after方法-->
</aop:aspect>
</aop:config>
</beans>
方式三,使用注解实现
User
package com.liu.service;
/**
* @version 1.0
* @description:TODO
* @Author:
* @date :2021/11/2 16:56
*/
public interface User {
public void add();
public void delete();
public void update();
public void query();
}
package com.liu.service;
/**
* @version 1.0
* @description:TODO
* @Author:
* @date :2021/11/2 16:57
*/
public class userServiceImpl implements User {
@Override
public void add() {
System.out.println("userServiceImpl.add");
}
@Override
public void delete() {
System.out.println("userServiceImpl.delete");
}
@Override
public void update() {
System.out.println("userServiceImpl.update");
}
@Override
public void query() {
System.out.println("userServiceImpl.query");
}
}
Annopc
package com.liu.DIy;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
/**
* @version 1.0
* @description:TODO
* @Author:
* @date :2021/11/2 18:08
*/
//使用注解方式实现AOP
@Aspect //标注这个类是一个切面
public class Annopc {
/*
@Before("execution(* com.liu.service.userServiceImpl.*(..))")
public void before() {
System.out.println("Annopc.before");
}
@After("execution(* com.liu.service.userServiceImpl.*(..))")
public void after() {
System.out.println("Annopc.after");
}
*/
//在环绕增强中,我们可以给定一个参数,代表我们要获取处理切入的点
@Around("execution(* com.liu.service.userServiceImpl.*(..))")
public void around(ProceedingJoinPoint jp) throws Throwable {
System.out.println("before");
Signature signature = jp.getSignature();
System.out.println(signature);
Object proceed = jp.proceed();
System.out.println("after");
}
}
<?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: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/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<bean id="userServiceImpl" class="com.liu.service.userServiceImpl"/>
<bean id="before" class="com.liu.Log.Beforelog"/>
<bean id="after" class="com.liu.Log.Afterlog"/>
<!--方式三-->
<bean id="annopc" class="com.liu.DIy.Annopc"/>
<!--开启注解支持,开启自动代理-->
<aop:aspectj-autoproxy/>
</beans>
11、整合mybatis
方式一
需要导入的依赖
<dependencies>
<!--springmvc-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.11</version>
</dependency>
<!--junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!--mybaits-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<!--spring-jdbc-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.11</version>
</dependency>
<!-- mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</version>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
</dependencies>
userMapper
package com.liu.mapper;
import com.liu.pojo.User;
import java.util.*;
public interface userMapper {
List<User> queryAll();
}
userMapperImpl
package com.liu.mapper;
import com.liu.pojo.User;
import org.mybatis.spring.SqlSessionTemplate;
import java.util.List;
public class userMapperImpl implements userMapper {
private SqlSessionTemplate sqlSessionTemplate;
//创建一个set方法,方便时实现注入
public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
this.sqlSessionTemplate = sqlSessionTemplate;
}
@Override
public List<User> queryAll() {
userMapper mapper = sqlSessionTemplate.getMapper(userMapper.class);
return mapper.queryAll();
}
}
userMapper.xml
<?xm1 version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.liu.mapper.userMapper">
<select id="queryAll" resultType="User">
select *
from user
</select>
</mapper>
POJO
mybatis-config.xml
<?xm1 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.liu.pojo"/>
</typeAliases>
</configuration>
spring.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">
<!--DataSource:使用Spring的数据源替换Mybatis的数据源,连接到数据库 -->
<bean id="DataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url"
value="jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8&useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</bean>
<!--sqlSessionFactory,-->
<bean id="sqlSessoionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="DataSource"/>
<!--定位mybatis配置文件-->
<property name="configLocation" value="classpath:mybaits-config.xml"/>
<!--定位mapper文件-->
<property name="mapperLocations" value="classpath:com/liu/mapper/userMapper.xml"/>
</bean>
<!--sqlSessionTemplate,也就是sqlsession,-->
<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessoionFactory"/> <!--构造器注入-->
</bean>
<bean id="userMapper" class="com.liu.mapper.userMapperImpl">
<property name="sqlSessionTemplate" ref="sqlSessionTemplate"/> <!--set注入-->
</bean>
</beans>
我遇到的问题
[com.sun.org.apache.xerces.internal.impl.io.MalformedByteSequenceException: 2 字节的 UTF-8 序列的字节 2 无效]
xml文件里面不能出现中文注释,
无法找到Mapper文件,由于java不会自动到处src/main/java下的xml文件,需要在Pom中配置,防止配置文件无法导出
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
实现步骤
- 创建POJO类
- 编写mapper接口,编写mapper接口实现类,编写mapper.xml
- 创建Spring配置文件
- 创建Datasource
- 创建SqlSessionFactory,并未datasource注入上面创建的DataSource
- 创建SqlSessionTemplate,通过有参构造器方法注入SqlSessionFactory
- 创建mybatis的其他配置文件(Setting,TypeAliases等)
- Test
个人总结:连接数据库的部分,写入到spring中,通过一层一层的注入,实现创建SqlSessionFactory和SqlSessionTemlate,mapper实现类通过注入,创建sqlSessionTemplate实例化,最后调用mapper实现类,完成对数据库的访问。
方式二
其他不变
添加一个UserMapperImpl2
package com.liu.mapper;
import com.liu.pojo.User;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import java.util.List;
/**
* @version 1.0
* @description:TODO
* @Author:
* @date :2021/11/3 14:52
*/
public class userMapperImpl2 extends SqlSessionDaoSupport implements userMapper {
@Override
public List<User> queryAll() {
SqlSession sqlSession = getSqlSession();
return sqlSession.getMapper(userMapper.class).queryAll();
}
}
在spring里面添加对应的Bean
<bean id="Impl2" class="com.liu.mapper.userMapperImpl2">
<!--这里注入,是因为继承的SqlSessionDaoSupport的父类需要一个SqlSessionFactory,所以要注入-->
<property name="sqlSessionFactory" ref="sqlSessoionFactory"/>
</bean>
12、声明式事务
事务:ACID(原子性,一致性,隔离性,持久性)
要么都成功,要么都失败
声明式事务:AOP
编程式事务:在代码中,进行事物的管理
配置事务的可以防止数据不一致的情况
实现
在spring配置文件中配置
<!--结合AOP实现事务的织入-->
<!--配置事务 TX-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<!--给那些方式配置事务-->
<tx:attributes>
<tx:method name="add" propagation="REQUIRED"/>
<tx:method name="delete" propagation="REQUIRED"/>
<tx:method name="update" propagation="REQUIRED"/>
<tx:method name="query" read-only="true"/>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<!--配置事务切入-->
<aop:config>
<aop:pointcut id="pc" expression="execution(* com.liu.mapper.*.*(..))"/> <!--创建一切入点-->
<aop:advisor advice-ref="txAdvice" pointcut-ref="pc"/> <!--将上面创建的事务织入到切入点-->
</aop:config>
mapper接口实现类
package com.liu.mapper;
import com.liu.pojo.User;
import org.mybatis.spring.SqlSessionTemplate;
import java.util.List;
public class userMapperImpl implements userMapper {
private SqlSessionTemplate sqlSessionTemplate;
//创建一个set方法,方便时实现注入
public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
this.sqlSessionTemplate = sqlSessionTemplate;
}
@Override
public List<User> queryAll() {
//没有事务处理的时候,尽管报错了,但addUser还是会成功,
//添加事务之后,要么都成功,要么都失败
userMapper mapper = sqlSessionTemplate.getMapper(userMapper.class);
mapper.addUser(new User(7,"刘正伟","1234567"));
mapper.deleteUser(7);
return mapper.queryAll();
}
@Override
public int addUser(User user) {
return sqlSessionTemplate.getMapper(userMapper.class).addUser(user);
}
@Override
public int deleteUser(int id) {
return sqlSessionTemplate.getMapper(userMapper.class).deleteUser(id);
}
}
/>
<tx:method name=“update” propagation=“REQUIRED”/>
<tx:method name=“query” read-only=“true”/>
<tx:method name="*" propagation=“REQUIRED”/>
</tx:attributes>
</tx:advice>
<!--配置事务切入-->
<aop:config>
<aop:pointcut id="pc" expression="execution(* com.liu.mapper.*.*(..))"/> <!--创建一切入点-->
<aop:advisor advice-ref="txAdvice" pointcut-ref="pc"/> <!--将上面创建的事务织入到切入点-->
</aop:config>
mapper接口实现类
```java
package com.liu.mapper;
import com.liu.pojo.User;
import org.mybatis.spring.SqlSessionTemplate;
import java.util.List;
public class userMapperImpl implements userMapper {
private SqlSessionTemplate sqlSessionTemplate;
//创建一个set方法,方便时实现注入
public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
this.sqlSessionTemplate = sqlSessionTemplate;
}
@Override
public List<User> queryAll() {
//没有事务处理的时候,尽管报错了,但addUser还是会成功,
//添加事务之后,要么都成功,要么都失败
userMapper mapper = sqlSessionTemplate.getMapper(userMapper.class);
mapper.addUser(new User(7,"刘正伟","1234567"));
mapper.deleteUser(7);
return mapper.queryAll();
}
@Override
public int addUser(User user) {
return sqlSessionTemplate.getMapper(userMapper.class).addUser(user);
}
@Override
public int deleteUser(int id) {
return sqlSessionTemplate.getMapper(userMapper.class).deleteUser(id);
}
}