一、Spring
1、简介
-
Spring:春天------>给软件行业带来了春天!
-
2002,首次推出了Spring框架的雏形:interface21框架!
-
Spring框架即以interface21框架为基础,经过重新设计,并不断丰富其内涵,于2004年3月24日发布了1.0正式版。
-
Rod Johnson,Spring Framework创始人,著名作者。很难想象Rod Johnson的学历,真的让好多人大吃一惊,他是悉尼大学的博士,然而他的专业不是计算机,而是音乐学。
-
Spring理念:使现有的技术更加容易使用,本身是一个大杂烩,整合了现有的技术框架!
-
SSH:Struct2 + Spring + Hibernate!
-
SSM:SpringMVC + Spring + Mybatis!
-
官网:https://spring.io/projects/spring-framework#overview
-
官方下载地址:https://repo.spring.io/release/org/springframework/spring/
-
GitHub:https://github.com/spring-projects/spring-framework
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.22</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.22</version>
</dependency>
2、优点
- Spring时一个开源的免费框架(容器)
- Spring时一个清亮及的,非入侵传的框架
- 控制反转(IOC),面向切面编程(AOP)
- 支持事务处理,对框架整合的支持
总结Spring就是一个轻量级的控制反转(IOC)和面向切面编程(AOP)的框架
3、组成
4、拓展
- 现代化的Java开发!就是面向spring的开发。
- Spring Boot
- 一个快速开发的脚手架
- 基于SpringBoot可以快速的开发单个微服务
- 约定大于配置
- Spring Cloud
- SpringCloud是基于SpringBoot实现的。
因为现在大多数公司都在使用SpringBoot进行快速开发,学习SpringBoot的前提,需要完全掌握Spring及SpringMVC!承上启下的作用!
弊端:发展了太久之后,违背了原来的理念!配置十分繁琐,人称:“配置地狱!”
二、IOC理论推导
1、UserDao接口
package com.jjl.dao;
public interface UserDao {
void getUser();
}
2、UserDaoImpl实现类
package com.jjl.dao;
public class UserDaoImpl implements UserDao{
public void getUser(){
System.out.println("默认获取用户的数据");
}
}
3、UserService业务接口
package com.jjl.service;
public interface UserService {
void getUser();
}
4、UserServiceImpl业务实现类
public class UserServiceImpl implements UserService {
private UserDao userDao = new UserDaoImpl();
public void getUser() {
userDao.getUser();
}
}
5、测试
public class MyTest {
public static void main(String[] args) {
//用户实际调用的是业务层,dao层他们不需要接触!
UserService userService = new UserServiceImpl();
userService.getUser();
}
}
在我们之前的业务中,用户的需求可能会影响我们原来的代码,我们需要根据用户的需求去修改原代码!如果程序代码量十分大,修改一次的成本代价十分昂贵!
我们使用一个Set接口实现,已经发生了革命性的变化!
package com.jjl.service;
import com.jjl.dao.UserDao;
public class UserServiceImpl implements UserService{
private UserDao userDao;
public void setUserDao(UserDao userDao){
this.userDao=userDao;
}
public void getUser() {
userDao.getUser();
}
}
这样无论有多少个实现类,都不用修改业务层,只需要给业务层传要调用的实现类就好,
当需要横向扩展业务时,只需要写相应的业务实现类,然后去直接调用就好,不会修改程序整体架构。
- 之前,程序是主动创建对象!控制权在程序猿手上!
- 使用了set注入后,程序不再具有主动性,而是变成了被动的接收对象!
这种思想,从本质上解决了问题,我们程序猿不用再去管理对象的创建了。系统的耦合性大大降低~,可以更加专注的在业务的实现上!这是IOC的原型!
IOC本质
控制反转IoC(Inversion of Control),是一种设计思想,DI(依赖注入)是实现IoC的一种方法,也有人认为DI只是IoC的另一种说法。没有IoC的程序中,我们使用面向对象编程,对象的创建与对象间的依赖关系完全硬编码在程序中,对象的创建由程序自己控制,控制反转后将对象的创建转移给第三方,个人认为所谓控制反转就是:获得依赖对象的方式反转了。
采用XML方式配置Bean的时候,Bean的定义信息是和实现分离的,而采用注解的方式可以把两者合为一体,Bean的定义信息直接以注解的形式定义在实现类中,从而达到了零配置的目的。
控制反转是一种通过描述(XML或注解)并通过第三方去生产或获取特定对象的方式。在Spring中实现控制反转的是IoC容器,其实现方法是依赖注入(Dependency Injection,DI)。
三、HelloSpring
1、新建一个maven项目,编写实体类
package com.jjl.pojo;
public class Hello {
private String str;
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
@Override
public String toString() {
return "Hello{" +
"str='" + str + '\'' +
'}';
}
}
2、编写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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 使用spring来创建对象,在spring这些都称为Bean
类型 变量名 = new 类型();
bean = 对象 new Hello();
id = 变量名
class = new 的对象;
property 相当与给对象的属性设置值
-->
<bean id="hello" class="com.jjl.pojo.Hello">
<property name="str" value="Spring"/>
</bean>
</beans>
3、测试
import com.jjl.pojo.Hello;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
public static void main(String[] args) {
//获取Spring的上下文对象!
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//我们的对象现在都在Spring中管理了,我们要使用,直接去里面取出来就可以了
Hello hello = (Hello) context.getBean("hello");
System.out.println(hello.toString());
}
}
四、IOC创建对象的方式
1、使用无参构造创建对象
2、假设哟啊使用有参构造创建
方法一:下标赋值
<bean id="user" class="com.jjl.pojo.User">
<constructor-arg index="0" value="xl"/>
</bean>
方法二: 通过参数类型创建,但是要保证实体类里没有相同类型的属性
<!-- 通过参数类型创建,但是要保证实体类里没有相同类型的属性-->
<bean id="user" class="com.jjl.pojo.User">
<constructor-arg type="java.lang.String" value="xl"/>
</bean>
方法三:通过参数名:
<bean id="user" class="com.jjl.pojo.User">
<constructor-arg name="name" value="xl"/>
</bean>
五、Spring配置
1、别名
2、bean的配置
<!--
id : bean 的唯一标识符,也就是相当于我们学的对象名
class:bean对象所对应的权限定名:包名.类型
name:也是别名,而且name可以同时取多个别名
-->
<bean id="user" class="com.jjl.pojo.User" name="user2 u1,u2">
<constructor-arg name="name" value="xl"/>
</bean>
3、import
这个import。一般用于团队开发,它可以将多个配置文件,导入合并为一个。
假设,现在项目中有多个人开发,这三个人负责不同的类开发,不同的类需要注册在不同的bean中,我们可以利用import将所有人的beans.xml合并为一个总的!
- 张三
- 李四
- 王五
- applicationContext.xml
使用的时候,直接使用总的配置就可以了。
六、依赖注入
1、结构器注入
2、set方法注入
- 依赖注入:set注入
- 依赖:bean对象的创建依赖于容器
- 注入:bean对象中的所有属性,由容器来注入
【环境搭建】
1、复杂类型
package com.jjl.pojo;
public class Address {
private String Address;
public String getAddress() {
return Address;
}
public void setAddress(String address) {
Address = address;
}
@Override
public String toString() {
return "Address{" +
"Address='" + Address + '\'' +
'}';
}
}
2、真实测试对象
package com.jjl.pojo;
import java.util.*;
public class Student {
private String name;
private Address address;
private String[] book;
private List<String> hobbys;
private Map<String,String> card;
private Set<String> games;
private String wife;
private Properties info;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String[] getBook() {
return book;
}
public void setBook(String[] book) {
this.book = book;
}
public List<String> getHobbys() {
return hobbys;
}
public void setHobbys(List<String> hobbys) {
this.hobbys = hobbys;
}
public Map<String, String> getCard() {
return card;
}
public void setCard(Map<String, String> card) {
this.card = card;
}
public Set<String> getGames() {
return games;
}
public void setGames(Set<String> games) {
this.games = games;
}
public String getWife() {
return wife;
}
public void setWife(String wife) {
this.wife = wife;
}
public Properties getInfo() {
return info;
}
public void setInfo(Properties info) {
this.info = info;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", address=" + address +
", book=" + Arrays.toString(book) +
", hobbys=" + hobbys +
", card=" + card +
", games=" + games +
", wife='" + wife + '\'' +
", info=" + info +
'}';
}
}
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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="student" class="com.jjl.pojo.Student">
<property name="name" value="jjl"/>
</bean>
</beans>
4、测试类
import com.jjl.pojo.Student;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Student student = (Student) context.getBean("student");
System.out.println(student.getName());
}
}
5、完善注入信息
<?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="address" class="com.jjl.pojo.Address">
<property name="address" value="四川成都"/>
</bean>
<bean id="student" class="com.jjl.pojo.Student">
<!--第一种,谱图注入 value-->
<property name="name" value="jjl"/>
<!--第二种,Bean注入,ref-->
<property name="address" ref="address"/>
<!--数组注入-->
<property name="book">
<array>
<value>《西游记》</value>
<value>《红楼梦》</value>
<value>《水浒传》</value>
<value>《三国演义》</value>
</array>
</property>
<!--list注入-->
<property name="hobbys">
<list>
<value>听歌</value>
<value>代码</value>
<value>电影</value>
</list>
</property>
<!--map注入-->
<property name="card">
<map>
<entry key="身份证" value="123456789012345678"/>
<entry key="银行卡" value="123456789012345123"/>
</map>
</property>
<!--set注入-->
<property name="games">
<set>
<value>LOL</value>
<value>cs</value>
<value>BOB</value>
<value>COC</value>
</set>
</property>
<!--null注入-->
<property name="wife">
<null/>
</property>
<!--Properties-->
<property name="info">
<props>
<prop key="driver">18302020426</prop>
<prop key="url">http://</prop>
<prop key="username">xl</prop>
<prop key="password">12341234</prop>
</props>
</property>
</bean>
</beans>
6、测试
import com.jjl.pojo.Student;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Student student = (Student) context.getBean("student");
System.out.println(student.toString());
/*
Student{
name='jjl',
address=Address{Address='四川成都'},
book=[《西游记》, 《红楼梦》, 《水浒传》, 《三国演义》],
hobbys=[听歌, 代码, 电影],
card={身份证=123456789012345678, 银行卡=123456789012345123},
games=[LOL, cs, BOB, COC],
wife='null',
info={
password=12341234, url=http://, driver=18302020426, username=xl
}
}
* */
}
}
3、拓展方式注入
P命名空间和c命名空间
官方解释:
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-p-namespace
-
使用
导入三方约束
xmlns:p=“http://www.springframework.org/schema/p”
xmlns:c=“http://www.springframework.org/schema/c”
-
测试
User user = (User) context.getBean(“user”); == User user = context.getBean(“user”, User.class);
4、bean的作用域
1、单例模式(Spring默认机制)
<bean id="user2" class="com.jjl.pojo.User" c:age="18" c:name="jjl" scope="singleton"/>
2、原型模式,每次从容器中get的时候,都会产生一个新的对象!
<bean id="user2" class="com.jjl.pojo.User" c:age="18" c:name="jjl" scope="prototype"/>
3、其余的request、session、application、websocket,这些只能在web开发中使用到!
七、Bean的自动装配
- 自动装配是spring满足bean依赖一种方式
- spring会在上下文中自动寻找,并自动给bean装配属性
在spring中由三种装配的方式
- 在xml中显示的配置
- 在Java中显示配置
- 隐式的自动装配bean【重点】
1、测试
不使用自动装配
<bean id="cat" class="com.jjl.pojo.Cat"/>
<bean id="dog" class="com.jjl.pojo.Dog"/>
<bean id="people" class="com.jjl.pojo.People">
<property name="name" value="xl"/>
<property name="cat" ref="cat"/>
<property name="dog" ref="dog"/>
</bean>
2、ByName自动装配
<bean id="cat" class="com.jjl.pojo.Cat"/>
<bean id="dog" class="com.jjl.pojo.Dog"/>
<!--
byname:会自动在容器上文中查找,和自己对象set方法后面的值对应的bean id
-->
<bean id="people" class="com.jjl.pojo.People" autowire="byName">
<property name="name" value="xl"/>
</bean>
3、ByName自动装配
<bean class="com.jjl.pojo.Cat"/>
<bean class="com.jjl.pojo.Dog"/>
<!--
bytype:会自动在容器上文中查找,和自己对象属性类型相同的bean id
-->
<bean id="people" class="com.jjl.pojo.People" autowire="byType">
<property name="name" value="xl"/>
</bean>
小结:
- byname的时候,需要保证所有bean的id唯一,并且这个bean需要和自动注入的属性的set方式的值一致!
- byname的时候,需要保证所有bean的class唯一,并且这个bean需要和自动注入的属性类型一致!
4、使用注解实现自动装配
jdk1.5支持的注解,spring2.5就开始支持了
要使用注解须知:
- 导入约束
xmlns:context=“http://www.springframework.org/schema/context” - 配置注解的支持
<context:annotation-config/>
<?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方法了,前提是自动装配的属性在IOC(spring)容器中存在,且符合名字Byname!
扩展:
@Nullable: 字段标记了这个注释,说明这个字段可以为null
public @interface Autowired {
boolean required() default true;
}
测试:
//如果显示定义了Autowired的required属性false,说明这个对象可以为null,否则不允许为空
@Autowired(required = false)
private Cat cat;
@Autowired
private Dog dog;
private String name;
/*不允许为空*/
public People(@Nullable String name) {
this.name = name;
}
如果@Autowired自动装配的环境比较复杂,自动装配无法通过一个注解【@Autowired】完成的时候,我们可以使用@Qualifier(value=“xxx”)去配置@Autowired的使用,指定一个唯一的bean对象注入。
@Autowired
@Qualifier(value = "cat111")
private Cat cat;
@Autowired
@Qualifier(value = "dog222")//起别名
private Dog dog;
<bean id="cat" class="com.jjl.pojo.Cat"/>
<bean id="cat111" class="com.jjl.pojo.Cat"/>
<bean id="dog222" class="com.jjl.pojo.Dog"/>
@Resource
@Resource(name = "cat1")
private Cat cat;
@Resource
private Dog dog;
@Resource和@Autowired的区别:
- 都是用来自动装配的,都可以放在属性字段上
- @Autowired通过bytype的方式实现,
- @Resource默认通过byname的方式实现,如果找不到名字,则通过bytype实现。
- 执行顺序不同:Resource默认通过byname的方式实现,@Autowired通过bytype的方式实现。
八、使用注解开发
在spring4之后,要使用注解开发,必须要保证aop的包导入了
使用注解需要导入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>
1、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"
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.jjl.pojo"/>
<context:annotation-config/>
</beans>
2、属性如何注入
package com.jjl.pojo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
//@Component组件,这个注解等价于<bean id="user" class="com.jjl.pojo.User"/>
@Component
public class User {
@Value("xl")//这个注解是给属性赋值,相当于public String name="xl",或者相当于<property name="name" value="xl"/>
public String name;
public String pwd;
//如果有set方法,@Value也可以放在set方法上
@Value("123qwe")
public void setPwd(String pwd) {
this.pwd = pwd;
}
}
测试
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
User user = context.getBean("user", User.class);
System.out.println(user.name);
System.out.println(user.pwd);
}
}
3、衍生的注解
@Component 有几个衍生注解,我们在web开发中,会按照mvc三层架构分层
- dao【@Repository】
- service【@Service】
- controller【@Controller】
【@Component】、【@Repository】、【@Service】、【@Controller】这四个注解功能是一样的,都是代表将某个类注册到spring中,装配Bean
4、自动装配
同上
5、作用域
6、小结
- xml与注解:
- xml更加万能,适用于任何场景,维护简单方便
- 注解不是自己类使用不了,维护相对复杂
- xml与注解最佳实践
- xml用来挂历bean;
- 注解只负责完成属性的注入;
- 我们在使用的过程中只需要注意一个问题,必须让注解生效,就需要开启注解的支持
<!--指定要扫面的包,这个包下面的注解就会生效--> <context:component-scan base-package="com.jjl"/> <context:annotation-config/>`
九、使用Java的方式配置spring
我们现在要我完全不适用spring的xml配置,全部交给java来做
JavaConfig是Spring是的一个子项目,在spring4之后,他成为了一个核心功能
实体类
package com.jjl.pojo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
//这里这个注解的意思,就是说明这个类被spring接管了,注册到了容器中
@Component
public class User {
private String name;
public String getName() {
return name;
}
@Value("jjl")//属性注入值
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
'}';
}
}
spring配置类
package com.jjl.config;
import com.jjl.pojo.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
/*
* 这个也会被spring容器托管,注册到容器中,因为它本来就是一个Component
* @Configuration代表这是一个配置类,就和我们之前看的beans.xml是一样的
* @Configuration和@ComponentScan("com.jjl.pojo")二选一即可
* */
@Configuration
@ComponentScan("com.jjl.pojo")
@Import(MyConfig2.class)//导入另一个类
public class MyConfig {
//注册一个bean,九相当于我们之前写的一个bean标签,
//这个方法的名字,就相当于bean标签的id属性
//这个方法的返回值,就相当于bean标签的class属性
@Bean
public User getUser(){
return new User();//就是返回要注入到的bean对象
}
}
测试类
import com.jjl.config.MyConfig;
import com.jjl.pojo.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class MyText {
public static void main(String[] args) {
//如果完全使用了配置类方式去做,我们就只能通过AnnotationConfig上下文来获取容器,通过配置类的class对象加载
ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
User user = context.getBean("getUser", User.class);
System.out.println(user.getName());
}
}
十、代理模式
代理模式是springAOP的底层!【springAOP和springMVC】
代理模式的分类:
- 静态代理
- 动态代理
1、静态代理
角色分析:
- 抽象角色:一般会使用接口或者抽象类来解决
- 真实角色:被代理的角色
- 代理角色:代理真实角色,代理真实角色后,我们一般会做一些附属操
- 客户:访问代理对象的人
代理步骤:
1、接口
package com.jjl.demo01;
//租房
public interface Rent {
public void rent();
}
2、真实角色
package com.jjl.demo01;
//房东
public class Host implements Rent {
@Override
public void rent() {
System.out.println("房东要出租房子");
}
}
3、代理角色【使用构造器方式】
package com.jjl.demo01;
public class Proxy implements Rent{
private Host host;
public Proxy() {
}
public Proxy(Host host) {
this.host = host;
}
@Override
public void rent() {
host.rent();
seeHouse();
hetong();
fare();
}
//看房
public void seeHouse(){
System.out.println("中介带你看房");
}
//合同
public void hetong(){
System.out.println("签租赁合同");
}
//收中介费
public void fare(){
System.out.println("收中介费");
}
}
4、客户端访问代理角色
package com.jjl.demo01;
public class Client {
public static void main(String[] args) {
//房东要租房子
Host host = new Host();
//代理,中介帮房东出租房子,但是呢,代理角色一般会有一些附加属性
Proxy proxy = new Proxy(host);
//你不用面对房东,直接找中介即可
proxy.rent();
//找中介看房
proxy.seeHouse();
//和中介签合同
proxy.hetong();
//付款给中介
proxy.fare();
}
}
代理模式的好处
- 可以是真实角色的操作更加纯粹,不用去关注一些公共的业务
- 公共也就交给代理角色,实现了业务的分工
- 公共业务发生扩展的时候,方便集中管理
缺点:
- 一个真实角色就会产生一个代理角色,代理两翻倍,开发效率降低
2、加深理解
测试场景:在不修改源业务层代码的情况下,给业务层类新增一些功能,这里可以使用代理
- 接口类,有增删改查四个方法
package com.jjl.demo02; public interface UserService { public void add(); public void delete(); public void update(); public void query(); }
- 源接口实现类
package com.jjl.demo02; public class UserServiceImpl implements UserService{ @Override public void add() { System.out.println("增加了一个用户"); } @Override public void delete() { System.out.println("删除了一个用户"); } @Override public void update() { System.out.println("修改了一个用户"); } @Override public void query() { System.out.println("查询了一个用户"); } }
- 先需要给接口实现类的每一个方法里新增一个日志输出,不修改源代码。
新增代理类【使用set方式】package com.jjl.demo02; public class UserServiceProxy implements UserService{ private UserServiceImpl userService; public void setUserService(UserServiceImpl userService) { this.userService = userService; } @Override public void add() { log("add"); userService.add(); } @Override public void delete() { log("delete"); userService.delete(); } @Override public void update() { log("update"); userService.update(); } @Override public void query() { log("query"); userService.query(); } //加一个日志方法 public void log(String msg){ System.out.println("使用了"+msg+"方法"); } }
3、动态代理
- 动态代理和静态角色一样
- 动态代理的代理类是动态生成的,不是我们直接写好的
- 动态代理分为两大类:基于接口的动态代理,基于类的动态代理
- 基于接口----JDK动态代理【我们使用这个】
- 基于类:cglib
- java字节码实现:javasist
需要了解两个类:Proxy(代理),InvocationHandler:是代理实例的调用处理程序 实现的接口
案例一:租房
- 接口
package com.jjl.demo03; //租房 public interface Rent { public void rent(); }
- 真实实现类
package com.jjl.demo03; //房东 public class Host implements Rent { @Override public void rent() { System.out.println("房东要出租房子"); } }
- 动态代理类
package com.jjl.demo03; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; //会用这个类自动生成代理类 public class ProxyInvocationHandler implements InvocationHandler { private Rent rent; public void setRent(Rent rent) { this.rent = rent; } /* Foo f = (Foo) Proxy.newProxyInstance(Foo.class.getClassLoader(), new Class[] { Foo.class }, handler) */ //生成得到代理类 public Object getProxy(){ //Proxy.newProxyInstance:生成一个代理对象 return Proxy.newProxyInstance( //this.getClass().getClassLoader():加载类的位置 //rent.getClass().getInterfaces():表示代理的接口是哪一个 this.getClass().getClassLoader(), rent.getClass().getInterfaces(),this ); } //处理代理实例,并返回结果 @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { seeHouse(); //动态代理的本质就是使用反射机制实现 Object result = method.invoke(rent, args); fare(); return result; } public void seeHouse(){ System.out.println("中介带看房子"); } public void fare(){ System.out.println("收中介费"); } }
- 测试:
package com.jjl.demo03; public class Client { public static void main(String[] args) { //真实角色 Host host = new Host(); //代理角色:现在没有 ProxyInvocationHandler pih = new ProxyInvocationHandler(); //通过调用程序处理角色,来处理我们要调用的接口对象 pih.setRent(host); Rent proxy =(Rent) pih.getProxy();//这里的proxy就是动态生成的 proxy.rent(); } }
案例二:使用上面静态代理的User类
-
万能的静态代理类
package com.jjl.demo04; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; //会用这个类自动生成代理类 //万能的动态代理类,只需要修改被代理的接口【target】、要新增内容的类要新增内容的类即可 public class ProxyInvocationHandler implements InvocationHandler { //被代理的接口 private Object target; public void setTarget(Object target) { this.target = target; } //生成得到代理类 public Object getProxy(){ return Proxy.newProxyInstance( this.getClass().getClassLoader(), target.getClass().getInterfaces(),this ); } //处理代理实例,并返回结果 @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { log(method.getName()); //动态代理的本质就是使用反射机制实现 Object result = method.invoke(target, args); return result; } //要新增内容的类 public void log(String msg){ System.out.println("执行了"+msg+"方法"); } }
-
测试类
package com.jjl.demo04; import com.jjl.demo02.UserService; import com.jjl.demo02.UserServiceImpl; public class Client { public static void main(String[] args) { //真实角色 UserServiceImpl userService = new UserServiceImpl(); //代理角色,不存在 ProxyInvocationHandler pih = new ProxyInvocationHandler(); pih.setTarget(userService);//设置要代理的对象 //动态生成代理类 UserService proxy = (UserService) pih.getProxy(); proxy.add(); proxy.delete(); } }
-
测试结果
总结
动态代理的好处
- 可以是真实角色的操作更加纯粹,不用去关注一些公共的业务
- 公共也就交给代理角色,实现了业务的分工
- 公共业务发生扩展的时候,方便集中管理
- 一个动态代理类,代理的是一个接口,一般就是对应的一类业务
- 一个动态代理类,可以代理多个类,只要实现了接口即可
十一、AOP
1、 什么是AOP
AOP(Aspect Oriented Programming)意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。
2 AOP在Spring中的作用
提供声明式事务;允许用户自定义切面
- 横切关注点:跨越应用程序多个模块的方法或功能。即是,与我们业务逻辑无关的,但是我们需要关注的部分,就是横切关注点。如日志,安全,缓存,事务等等…
- 切面(ASPECT):横切关注点被模块化的特殊对象。即,它是一个类。
- 通知(Advice):切面必须要完成的工作。即,它是类中的一个方法。
- 目标(Target):被通知对象。
- 代理(Proxy):向目标对象应用通知之后创建的对象。
- 切入点(PointCut):切面通知执行的“地点”的定义。
- 连接点(JointPoint):与切入点匹配的执行点。
SpringAOP中,通过Advice定义横切逻辑,Spring中支持5种类型的Advice:
即AOP在不改变原有代码的情况下,去增加新的功能。
3、使用spring实现Aop
【重点】使用aop置入,需要导入一个依赖包!
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.9.1</version>
</dependency>
1、方式一:使用spring的API接口【主要试springapi接口实现】
- 实体类接口
package com.jjl.service; public interface UserService { public void add(); public void delete(); public void update(); public void select(); }
- 接口实现类
package com.jjl.service; public class UserServiceImpl implements UserService{ @Override public void add() { System.out.println("增加了一个用户"); } @Override public void delete() { System.out.println("删除了一个用户"); } @Override public void update() { System.out.println("修改了一个用户"); } @Override public void select() { System.out.println("查询到了一个用户"); } }
- 前置增强类
package com.jjl.log;
import org.springframework.aop.MethodBeforeAdvice;
import java.lang.reflect.Method;
public class Log implements MethodBeforeAdvice {
//method:要执行的目标对象的方法
//Object:参数
//target:目标对象
@Override
public void before(Method method, Object[] args, Object target) throws Throwable {
System.out.println(target.getClass().getName()+"的"+method.getName()+"被执行了");
}
}
-
后置增强类
package com.jjl.log; import org.springframework.aop.AfterReturningAdvice; import java.lang.reflect.Method; 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); } }
-
新建spring配置xml文件 ,并注册类, 实现aop环绕增强类切入 , 注意导入约束
<?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 https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd"> <!--注册bean--> <bean id="userService" class="com.jjl.service.UserServiceImpl"/> <bean id="log" class="com.jjl.log.Log"/> <bean id="afterLog" class="com.jjl.log.AfterLog"/> <!--方式一:使用原生的Sping API接口--> <!--配置aop:需要导入aop的约束--> <aop:config> <!--切入点:execution表达式.execution(要执行的位置) (*【返回值任意】 com.jjl.service.UserServiceImpl【被插入的类】.*【的所有方法】(..)【的任意参数】)--> <aop:pointcut id="pointcut" expression="execution(* com.jjl.service.UserServiceImpl.*(..))"/> <!--执行环绕增加--> <!--将log这个类切入到pointcut上面--> <aop:advisor advice-ref="log" pointcut-ref="pointcut"/> <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/> </aop:config> </beans>
-
测试
2、方式二:自定义类来实现AOP【只要是切面定义】
- 延用方法一实现类
- 新增自定义增强类,编写两个切入点的方法
package com.jjl.diy; public class DiyPointCut { public void before(){ System.out.println("====自定义=====方法执行前=========="); } public void after(){ System.out.println("====自定义=====方法执行后=========="); } }
- 修改spring配置文件,并注册新增的增强类,配置AOP切入
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--注册bean-->
<bean id="userService" class="com.jjl.service.UserServiceImpl"/>
<!--方法二,自定义类-->
<bean id="diy" class="com.jjl.diy.DiyPointCut"/>
<aop:config>
<!--自定义切面,ref要引用的类-->
<aop:aspect ref="diy">
<!--切入点-->
<aop:pointcut id="point" expression="execution(* com.jjl.service.UserServiceImpl.*(..))"/>
<!--通知-->
<aop:before method="before" pointcut-ref="point"/>
<aop:after method="after" pointcut-ref="point"/>
</aop:aspect>
</aop:config>
</beans>
3、方式三,使用注解实现
- 延用方法一实现类
- 新增自定义增强类,并注解标记相应切入点,还可以进一步处理切入点
package com.jjl.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; //使用注解实现aop @Aspect //标注这个类是一个切面 public class AnnotationPointCut { @Before("execution(* com.jjl.service.UserServiceImpl.*(..))") public void before(){ System.out.println("=====方法执行前====="); } @After("execution(* com.jjl.service.UserServiceImpl.*(..))") public void After(){ System.out.println("====方法执行后===="); } //在环绕增强中,可以给定一个参数,代表我们要获取处理切入点 @Around("execution(* com.jjl.service.UserServiceImpl.*(..))") public void around(ProceedingJoinPoint jp) throws Throwable { System.out.println("环绕前"); //执行方法 jp.proceed(); System.out.println("环绕后"); } }
- 修改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" 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"> <!--注册bean--> <bean id="userService" class="com.jjl.service.UserServiceImpl"/> <!--方式三:--> <bean id="annotationPointCut" class="com.jjl.diy.AnnotationPointCut"/> <!--开启注解支持 实现方式: proxy-target-class="false",默认方式,表示使用JDK(可以不做配置); proxy-target-class="true",表示使用cglib--> <aop:aspectj-autoproxy proxy-target-class="false"/> </beans>
- 测试
十二、整合Mybatis
步骤:
1、导入相关jar包
- junit
- mybatis
- mysql数据库
- spring相关
- aop织入
- mybatis-spring【new】
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.10</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.22</version>
</dependency>
<!--spring操作jdbc-->
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.22</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<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>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
<scope>provided</scope>
</dependency>
</dependencies>
2、编写配置文件
3、测试
2、回忆mybatis
1、编写实体类
package com.jjl.pojo;
import lombok.Data;
@Data
public class User {
private int id;
private String name;
private String pwd;
}
2、编写核心配置文件
<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<!--configuration核心配置文件-->
<configuration>
<typeAliases>
<package name="com.jjl.pojo"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?userSSL=true&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="1234qwer"/>
</dataSource>
</environment>
</environments>
<mappers>
<!-- <mapper class="com.jjl.mapper.UserMapper"/>-->
<package name="com.jjl.mapper"/>
</mappers>
</configuration>
3、编写接口
package com.jjl.mapper;
import com.jjl.pojo.User;
import java.util.List;
public interface UserMapper {
public List<User> selectUser();
}
4、编写Mapper.xml
<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--configuration核心配置文件-->
<mapper namespace="com.jjl.mapper.UserMapper">
<select id="selectUser" resultType="user">
select * from user;
</select>
</mapper>
5、测试
import com.jjl.mapper.UserMapper;
import com.jjl.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class MyTest {
@Test
public void test() throws IOException {
String resources = "mybatis-config.xml";
InputStream in= Resources.getResourceAsStream(resources);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
SqlSession sqlSession = sqlSessionFactory.openSession(true);
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = mapper.selectUser();
for (User user : userList) {
System.out.println(user.toString());
}
sqlSession.close();
}
}
注意:
1、将两个xml文件中头部处的"UTF-8"改为“UTF8"
2、在porm.xml中添加
<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>
2、Mybatis-Spring
官网:http://mybatis.org/spring/zh/index.html
注意匹配版本
1、创建spring-dao.xml文件,编写数据源配置、sqlSessionFactory、sqlSessionTemplate
<?xml version="1.0" encoding="UTF8"?>
<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">
<!--DataSource:使用spring的数据源来替换Mybatis的配置
我们这里使用spring提供的jdbc:org.springframework.jdbc.datasource-->
<bean id="DataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?userSSL=true&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="1234qwer"/>
</bean>
<!--SqlSessionFactory-->
<bean id="SqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="DataSource"/>
<!--绑定Mybatis配置文件-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<!--注册-->
<property name="mapperLocations" value="classpath:com/jjl/mapper/*.xml"/>
</bean>
<!--SqlSessionTemplate:就是我们使用的sqlsession-->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<!--只能使用构造器注入sqlSessionFactory,因为它没有set方法-->
<constructor-arg index="0" ref="SqlSessionFactory"/>
</bean>
</beans>
2、调整mybatis配置文件mybatis-config.xml,只保留configuration核心配置文件别名配置。【可以将配这个配置也移交给spring-dao.xml文件】
<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<!--configuration核心配置文件-->
<configuration>
<typeAliases>
<package name="com.jjl.pojo"/>
</typeAliases>
</configuration>
3、编写接口实现类,主要实现数据库的相关操作
package com.jjl.mapper;
import com.jjl.pojo.User;
import org.mybatis.spring.SqlSessionTemplate;
import java.util.List;
public class UserMapperImpl implements UserMapper{
/*我们的所有操作,都使用sqlsession来执行,现在都使用sqlsessionTemplate*/
private SqlSessionTemplate sessionTemplate;
public void setSessionTemplate(SqlSessionTemplate sessionTemplate) {
this.sessionTemplate = sessionTemplate;
}
public List<User> selectUser(){
UserMapper mapper = sessionTemplate.getMapper(UserMapper.class);
return mapper.selectUser();
}
}
4、ApplicationContext.xml文件,将实现类注入到spring中
<?xml version="1.0" encoding="UTF8"?>
<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"/>
<!--sql配置-->
<bean id="userMapper" class="com.jjl.mapper.UserMapperImpl">
<property name="sessionTemplate" ref="sqlSession"/>
</bean>
</beans>
5、测试
import com.jjl.mapper.UserMapper;
import com.jjl.pojo.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
@Test
public void test() {
ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
UserMapper userMapper = context.getBean("userMapper", UserMapper.class);
for (User user : userMapper.selectUser()) {
System.out.println(user);
}
}
}
6、目录:
扩展:方式二
让接口实现类继承SqlSessionDaoSupport,就可以让实现类更加简化
package com.jjl.mapper;
import com.jjl.pojo.User;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import java.util.List;
public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper{
public List<User> selectUser() {
// SqlSession sqlSession = getSqlSession();
// UserMapper mapper = sqlSession.getMapper(UserMapper.class);
// return mapper.selectUser();
/*精简成一行*/
return getSqlSession().getMapper(UserMapper.class).selectUser();
}
}
ApplicationContext.xml文件,将实现类注入到spring中
<!--sql配置:方法二-->
<bean id="userMapper2" class="com.jjl.mapper.UserMapperImpl2">
<property name="sqlSessionFactory" ref="SqlSessionFactory"/>
</bean>
测试:
十三、声明式事务
1、回顾事务
- 把一组业务当成一个业务来做;要么都成功,要么都失败!
- 事务在项目开发中,十分的重要,涉及到数据的一致性问题,不能马虎!
- 确保完整性和一致性。
事务得ACID原则:
- 原子性
- 一致性
- 隔离性
- 多个业务可能操作同一个资源,防止数据损坏
- 持久性
- 事务一旦提交,无论系统发生什么问题,结果都不会再被影响,被持久化的写到存储器中!
2、spring中的事务管理
- 声明式事务:交由容器管理事务(AOP)
- 编程式事务:需要再代码中,进行事务的管理
Spring在不同的事务管理API之上定义了一个抽象层,使得开发人员不必了解底层的事务管理API就可以使用Spring的事务管理机制。Spring支持编程式事务管理和声明式的事务管理。
编程式事务管理
- 将事务管理代码嵌到业务方法中来控制事务的提交和回滚
- 缺点:必须在每个事务操作业务逻辑中包含额外的事务管理代码
声明式事务管理
- 一般情况下比编程式事务好用。
- 将事务管理代码从业务方法中分离出来,以声明的方式来实现事务管理。
- 将事务管理作为横切关注点,通过aop方法模块化。Spring中通过Spring AOP框架支持声明式事务管理。
添加增删的接口
package com.jjl.mapper;
import com.jjl.pojo.User;
import java.util.List;
public interface UserMapper {
public List<User> selectUser();
//添加一个用户
public int addUser(User user);
//删除一个用户
public int deleteUser(int id);
}
编写mybatis的sql
<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--configuration核心配置文件-->
<mapper namespace="com.jjl.mapper.UserMapper">
<select id="selectUser" resultType="user">
select * from user;
</select>
<insert id="addUser" parameterType="user">
insert into user (id, name,pwd) values (#{id}, #{name},#{pwd});
</insert>
<delete id="deleteUser" parameterType="int">
delete from user where id=#{id}
</delete>
</mapper>
编写接口实现类
package com.jjl.mapper;
import com.jjl.pojo.User;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import java.util.List;
public class UserMapperImpl extends SqlSessionDaoSupport implements UserMapper{
public List<User> selectUser() {
User user = new User(11, "小明", "1234");
UserMapper mapper = getSqlSession().getMapper((UserMapper.class));
addUser(user);
deleteUser(10);
return mapper.selectUser();
}
public int addUser(User user) {
return getSqlSession().getMapper(UserMapper.class).addUser(user);
}
public int deleteUser(int id) {
return getSqlSession().getMapper(UserMapper.class).deleteUser(id);
}
}
在spring-dao.xml中配置事务,注意引入tx
<?xml version="1.0" encoding="UTF8"?>
<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/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
https://www.springframework.org/schema/tx/spring-tx.xsd">
<!--DataSource:使用spring的数据源来替换Mybatis的配置
我们这里使用spring提供的jdbc:org.springframework.jdbc.datasource-->
<bean id="DataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?userSSL=true&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="1234qwer"/>
</bean>
<!--SqlSessionFactory-->
<bean id="SqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="DataSource"/>
<!--绑定Mybatis配置文件-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<!--注册-->
<property name="mapperLocations" value="classpath:com/jjl/mapper/*.xml"/>
</bean>
<!--SqlSessionTemplate:就是我们使用的sqlsession-->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<!--只能使用构造器注入sqlSessionFactory,因为它没有set方法-->
<constructor-arg index="0" ref="SqlSessionFactory"/>
</bean>
<!--配置声明式事务-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="DataSource"/>
</bean>
<!--结合AOP实现事务的织入-->
<!--配置事务通知-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<!--要给那些方法配置事务-->
<!--配置事务的传播特性-->
<tx:attributes>
<tx:method name="add" propagation="REQUIRED"/>
<tx:method name="delete" propagation="REQUIRED"/>
<tx:method name="query" read-only="true"/>
<tx:method name="update" propagation="REQUIRED"/>
<!--配置所有方法的事务-->
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<!--配置事务切入-->
<aop:config>
<aop:pointcut id="txPointCut" expression="execution(* com.jjl.mapper.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut" />
</aop:config>
</beans>
思考:
为什么需要事务?
- 如果不配置事务,可能存在数据提交不一致的情况;
- 如果我们不在Spring中去配置声明式事务,我们就需要在代码中手动配置事务!
- 事务在项目的开发中十分重要,涉及到数据的一致性和完整性问题,不容马虎!