Java-spring-复习

1、IOC创建对象的方式

1)默认方式,无参构造创建对象

2)使用有参构造创建对象

方法一,下标赋值

<bean id="user" class="edu.dj.pojo.User">
    <constructor-arg index="0" value="D J"/>
</bean>

第二种,根据属性类型赋值,不建议使用,可能会存在相同类型的属性

<bean id="user" class="edu.dj.pojo.User">
    <constructor-arg type="java.lang.String" value="丁 杰"/>
</bean>

第三种,直接通过参数名传值

<bean id="user" class="edu.dj.pojo.User">
    <constructor-arg name="name" value="DingJie"/>
</bean>

总结:在配置文件被加载的时候,容器中管理的对象已经初始化了

2、Spring配置

2.1 别名

<!--别名,如果添加了别名,我们也可以通过别名来获取对象-->
<alias name="user" alias="nancy"/>

2.2 Bean配置

<!--
    id:bean的唯一标识符,相当于对象名
    class:bean所对应的全限定名:包名+类型
    name:name也是别名,而且name可以取多个别名
-->
<bean id="useT" class="edu.dj.pojo.UserT" name="user2,user3;user4 user5">
    <property name="name" value="Spring学习"/>
</bean>

2.3 import导入

import一般用于团队开发,他可以将多个配置文件,导入合并为一个
假设,现在项目中有多个人开发,这三个人复制不同的类开发,不同的类注册在不同的bean中,我们可以利用
import将所有人的bean.xml文件合并为一个总的

  • 张三
  • 李四
  • 王五
  • applicationContext.xml
<import resource="beans.xml"/>
<import resource="beans2.xml"/>
<import resource="beans3.xml"/>

3、依赖注入(DI)

3.1 构造器注入

前面已经说过

3.2 Set方式注入

  • 依赖注入:Set注入
    • 依赖:bean对象的创建依赖于容器
    • 注入:bean对象的所有属性,由容器来注入

【环境搭建】

  1. 复杂类型
public class Address {
    private String address;

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}
  1. 真实测试对象
public class Student {
  private String name;
  private Address address;
  private String[] books;
  private List<String> hobbies;
  private Map<String, String> card;
  private Set<String> games;
  private String wife;
  private Properties info;
}
  1. 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="address" class="edu.dj.pojo.Address">
		<property name="address" value="中国"/>
	</bean>

	<bean id="student" class="edu.dj.pojo.Student">
		<!--1. 简单的数据注入 value-->
		<property name="name" value="丁杰"/>
		<!--2. 自定义数据类型注入 ref-->
		<property name="address" ref="address"/>
		<!--3. 数组注入 array value-->
		<property name="books">
			<array>
				<value>红楼梦</value>
				<value>西游记</value>
				<value>三国演义</value>
				<value>水浒传</value>
			</array>
		</property>
		<!--4. List注入  list value-->
		<property name="hobbies">
			<list>
				<value>看视频</value>
				<value>学python</value>
				<value>学Java</value>
			</list>
		</property>
		<!--5. Map注入  map entry-->
		<property name="card">
			<map>
				<entry key="身份证" value="342423423432423234"/>
				<entry key="银行卡" value="342423423432423234"/>
			</map>
		</property>
		<!--6. Set注入  set value-->
		<property name="games">
			<set>
				<value>LOL</value>
				<value>DotA</value>
				<value>COC</value>
				<value>BOB</value>
			</set>
		</property>
		<!--7. null注入  -->
		<property name="wife">
			<null/>
		</property>
		<!--8. Properties注入  -->
		<property name="info">
			<props>
				<prop key="学号">18488314</prop>
				<prop key="性别">男</prop>
				<prop key="籍贯">江苏</prop>
			</props>
		</property>

 	</bean>
</beans>
  1. 测试类
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());
    }
}

3.3 扩展方式注入

使用p命名空间和c命名空间方式进行注入

<!-- p命名空间输入,可以直接注入属性的值:properties -->
<bean id="user" class="edu.dj.pojo.User" p:name="丁杰" p:age="18"/>
<!-- c命名空间输入,可以通过构造器注入:construct-args -->
<bean id="user2" class="edu.dj.pojo.User" c:age="18" c:name="天啊"/>

注意:使用p命名和c命名空间注入需要添加约束

xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"

3.4 bean的作用域

  1. 单例模式(singleton Spring的默认机制)
<bean id="user2" class="edu.dj.pojo.User" c:age="18" c:name="天啊" scope="singleton"/>
  1. 原型模式:每次从容器中get时,都会产生一个新的对象
<bean id="user2" class="edu.dj.pojo.User" c:age="18" c:name="天啊" scope="prototype"/>
  1. request、session、application这些个只能在web开发中使用

4、Bean的自动装配

  • 自动装配时spring满足bean依赖一种方式
  • spring会在上下文中自动寻找,并自动给bean装配属性

在Spring中有三种自动装配的方式

  1. 在xml中显示的配置
  2. 在Java中显示配置
  3. 隐式的自动装配bean(重要)

4.1 测试

环境搭建:一个人有两个宠物

4.2 byName自动搭配

<!--	自动装配 byName:会自动在容器的上下文中查找,和自己对象set方法后面的值对应的bean id-->
<bean id="cat" class="edu.dj.pojo.Cat"/>
<bean id="dog" class="edu.dj.pojo.Dog"/>
<bean id="person" class="edu.dj.pojo.Person" autowire="byName">
  <property name="name" value="我是你爸爸"/>
</bean>

4.3 byType自动搭配

<bean id="cat" class="edu.dj.pojo.Cat"/>
<bean id="dog" class="edu.dj.pojo.Dog"/>
<!--	自动装配 byName:会自动在容器的上下文中查找,和自己对象属性类型相同的bean-->
<bean id="person" class="edu.dj.pojo.Person" autowire="byType">
  <property name="name" value="我是你爸爸"/>
</bean>

小结:

  • byName的时候,需要保证所有bean的id唯一,并且bean需要和自动注入的属性set方法的值一致
  • byType的时候,需要保证所有bean的class唯一,并且这个bean需要和自动注入的属性的类型一致

4.4 使用注解自动搭配

使用注解须知:
1.导入约束
2.配置注解的支持: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;
}

测试代码:

public class Person {
    @Autowired
    private Cat cat;
    //如果显示定义了Autowired的require属性为false,说明这个对象可以为null,否则不允许为空
    @Autowired(required = false)
    private Dog dog;
    private String name;
}

如果@Autowired自动装配环境比较复杂,自动装配无法通过一个注解【@Autowired】完成时,我们可以使用@Qualifier(value="xx")去配置@Autowired的使用,指定一个唯一的bean对象注入!

public class Person {
  @Autowired
  @Qualifier(value = "cat")
  private Cat cat;
  @Autowired
  @Qualifier(value = "dog")
  private Dog dog;
  private String name;
}

@Resource注解

public class Person {
  @Resource(name = "cat2")
  private Cat cat;
  @Resource
  private Dog dog;
  private String name;
}

@Resource和Autowired的区别:

  • 都是用来自动装配的,都可以放在属性字段上
  • @Autowired通过byType的方式实现,而且必须要求这个对象存在!【常用】
  • @Resource默认通过byName的方式实现,如果找不到名字,则通过byType! 如果两个都找不到的情况下,就报错!
  • 执行顺序不同:@Autowired通过byType的方式实现

5.使用注解开发

在spring4之后,要使用注解开发,必须要保证aop的包导入
img_1.pngimage
使用注解需要导入context约束,增加注解的支持
1.bean
2.属性如何注入

public class User {
    
//    相当于<property name="user" value="DingJie">
    @Value("DingJie")
    public String name;
}

3.衍生的注解
@Component有几个衍生注解,在web开发中,会按照mvc三层架构分层;

  • dao【@Repository】
  • service【@Service】
  • controller【@Controller】
    这4个注释功能一样,在不同的层使用相应的注释,都是代表将某个类注册到spring中,装配Bean

4.自动装配

- @Autowired:自动装配通过类型。名字
    如果Autowired不能通过唯一自动装配成功,则需要通过@Qualifier(value="xxx")
- @Nullable:字段标记了这个注解,说明这个字段可以为null;
- @Resource:自动装配通过名字。类型

5.作用域

//等价于<bean id="user" class="edu.dj.pojo.User">
@Component
//<bean id="user" class="edu.dj.pojo.User" scope="singleton"/>
@Scope("singleton")
public class User {
    //相当于<property name="user" value="DingJie">
    @Value("DingJie")
    public String name;
}

6.小结
xml与注解:

  • xml 更加万能,适用于各种场合!维护简单
  • 注解 不是自己的类使用不了,维护相对复杂!

xml和注解的最佳实践:

  • xml用来管理bean;
  • 注解只负责完成属性的注入;
  • 在使用的过程中,只需要注意:必须让注解生效,需要开启注解支持
<!--	指定要扫描的包,这个包下的注解就会生效-->
<context:component-scan base-package="edu.dj"/>
<!--	注解支持-->
<context:annotation-config/>

6.使用Java的方式配置Spring

我们现在完全不使用Spring的xml配置了,全权交给Java来做!
JavaConfig是Spring的一个子项目,在Spring4之后,它成为了一个核心的功能
实体类:

//这个注解的意思,就是说明这个类被Spring接管了,注册到容器中
@Component
public class User {
    private String name;

    public String getName() {
        return name;
    }

    @Value("DingJie132")//属性注入
    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                '}';
    }
}

配置类:

package edu.dj.config;

import edu.dj.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("edu.dj.pojo")
@Import(MyConfig1.class)
public class MyConfig {

    //注册一个Bean,就相当于我们之前写的一个bean
    //id:方法名
    //class:方法的返回值
    @Bean
    public User getUser(){
        return new User();//返回注入的到bean的对象
    }
}

测试类:

public class MyTest {
    public static void main(String[] args) {
        //如果完全使用配置类方式去做,我们就只能通过AnnotationConfig上下文来获取容器,通过配置类class获取对象
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
        User user = (User) context.getBean("getUser");
        System.out.println(user.toString());
    }
}

这种纯Java的配置,在SpringBoot中随处可见!!

7.代理模式

Spring AOP的底层:代理模式【SpringAOP和SpringMVC面试必问】
代理模式的分类:

  • 静态代理
  • 动态代理

7.1 静态代理

角色分析:

  • 抽象角色:一般会使用接口或者抽象类来解决
  • 真实角色:被代理的的角色
  • 代理角色:代理真实角色,代理真实角色后,会做一些附属操作
  • 客户:访问代理对象的人

代理模式的好处:

  • 可以使真实角色的操作更加纯粹,不用去关注一些公共的业务
  • 公共也就交给代理角色!实现了业务的分工
  • 公共业务发生扩展的时候,方便集中管理

代码步骤:
1.接口

public interface Rent {
    public void rent();
}

2.真实角色

public class Host implements Rent{
  @Override
  public void rent() {
    System.out.println("房东出租");
  }
}

3.代理角色

public class Proxy implements Rent{
    private Host host;
    public Proxy(){

    }
    public Proxy(Host host) {
        this.host = host;
    }

    @Override
    public void rent() {
        seeHouse();
        host.rent();
        contract();
        fare();
    }

    public void seeHouse(){
        System.out.println("中介带你看房");
    }

    public void fare(){
        System.out.println("收中介费");
    }

    private void contract(){
        System.out.println("签租赁合同");
    }
}

4.客户端访问代理角色

public class Client {
    public static void main(String[] args) {
        //房东要出租房子
        Host host = new Host();
        //代理,中介帮房东出租房子,但是呢?代理会有一些附属操作
        Proxy proxy = new Proxy(host);
        //客户不需要面对房东,直接找中介即可
        proxy.rent();
    }
}

缺点:

  • 一个真实角色就会产生一个代理角色;代码量会翻倍开发效率会降低

7.2 加深理解

img_2.pngimage

7.3 动态代理

  • 动态代理和静态代理角色一样
  • 动态代理的代理类是动态生成的,不是我们直接写好的
  • 动态代理分为两大类:基于接口的动态代理,基于类的动态代理
    • 基于接口:JDK动态代理
    • 基于类:cglib
    • Java字节码实现:Javasist

需要的两个类:Proxy:代理, InvocationHandler:调用处理程序

动态代理类的好处:

  • 可以使真实角色的操作更加纯粹,不用去关注一些公共的业务
  • 公共也就交给代理角色!实现了业务的分工
  • 公共业务发生扩展的时候,方便集中管理
  • 一个动态代理类代理的是一个接口,一般就是对应的一类事务
  • 一个动态代理类可以代理多个类,只要实现了同一个接口即可

8、 AOP

8.1 什么是AOP

AOP(Aspect Oriented Programming)面向对象编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。是OOP的延续,是函数式编程的一种衍生泛型,降低耦合,提高程序的重用性
image

8.2 AOP在spring中的作用

image
image

8.3 使用spring实现AOP

【重点】使用AOP织入,需要导入一个依赖包

<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.4</version>
</dependency>

方式一:使用spring的API接口
Advice类:

public class AfterExecuteMethodLog implements AfterReturningAdvice {

    //returnValue:返回值
    @Override
    public void afterReturning(Object returnValue, Method method, Object[] objects, Object target) throws Throwable {
        System.out.println("执行力"+method.getName()+"方法,返回值为:"+returnValue);
    }
}
/******************************************************/
public class Log implements MethodBeforeAdvice {

  //method:要执行的目标对象方法
  //args:参数
  //target:目标对象
  @Override
  public void before(Method method, Object[] objects, Object target) throws Throwable {
    System.out.println(target.getClass().getName()+"的"+method.getName()+"被执行了!!");
  }
}

配置文件

<!--	注册-->
<bean id="userService" class="edu.dj.service.UserServiceImpl"/>
<bean id="log" class="edu.dj.log.Log"/>
<bean id="afterLog" class="edu.dj.log.AfterExecuteMethodLog"/>

<!--	方式一:使用原生Spring API接口-->
<!--	配置aop:需要导入aop的约束-->
<aop:config>
<!--		切入点:在哪执行 expression:表达式  execution(需要执行的位置)-->
    <aop:pointcut id="pointcut" expression="execution(* edu.dj.service.UserServiceImpl.*(..))"/>
<!--		执行环绕增加-->
    <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
    <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
</aop:config>

测试类:

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        //动态代理 代理的是接口
        UserService userService = (UserService) context.getBean("userService");
        userService.add();
    }
}

方式二:自定义类实现AOP
自定义类

public class DIY {
    public void before(){
        System.out.println("======之前执行=======");
    }

    public void after(){
        System.out.println("======之后执行=======");
    }
}

配置文件

<bean id="diy" class="edu.dj.diy.DIY"/>
<aop:config>
<!--		自定义切面-->
    <aop:aspect ref="diy">
<!--		切入点-->
        <aop:pointcut id="point" expression="execution(* edu.dj.service.UserServiceImpl.*(..))"/>
<!--		通知-->
        <aop:before method="before" pointcut-ref="point"/>
        <aop:after method="after" pointcut-ref="point"/>
    </aop:aspect>
</aop:config>

方式三:使用注解实现

//方式三:使用注解方式实现AOP
//@Aspect标注这个类是一个切面
@Aspect
public class AnnotationPointCut {

    @Before("execution(* edu.dj.service.UserServiceImpl.*(..))")
    public void before(){
        System.out.println("======方式三:之前执行=======");
    }

    @After("execution(* edu.dj.service.UserServiceImpl.*(..))")
    public void after(){
        System.out.println("======方式三:之后执行=======");
    }

    @Around("execution(* edu.dj.service.UserServiceImpl.*(..))")
    public void around(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("======方式三:环绕前=======");

        //获得签名
        Signature signature = pjp.getSignature();
        System.out.println(signature);
        //执行方法
        Object proceed = pjp.proceed();
        System.out.println(proceed);

        System.out.println("======方式三:环绕后=======");
    }
}

配置文件

<!--	方式三:注解实现-->
<bean id="annotationPointCut" class="edu.dj.diy.AnnotationPointCut"/>
<!--	开启注解支持  JDK(Spring默认使用,proxy-target-class="false")  cglib(proxy-target-class="true")-->
<aop:aspectj-autoproxy proxy-target-class="false"/>

9 整合MyBatis

步骤:

  1. 导入相关jar包
    • junit
    • mybatis
    • mysql数据库
    • spring相关的
    • aop织入
    • mybatis-spring【new】
<dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.15</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.4</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.3.8</version>
    </dependency>
<!--		Spring操作数据,需要一个spring-jdbc-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>5.2.4.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.9.4</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>2.0.4</version>
    </dependency>
</dependencies>
  1. 编写配置文件
  2. 测试

9.1 复习MyBatis

  1. 编写实体类
import lombok.Data;
@Data
public class pojo {
    private int id;
    private String userName;
    private String password;
    private String realName;
}
  1. 编写核心配置文件
<?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>
	<environments default="development">
		<environment id="development">
			<transactionManager type="JDBC"/>
			<dataSource type="POOLED">
				<property name="driver" value="com.mysql.jdbc.Driver"/>
				<property name="url" value="jdbc:mysql://localhost:3306/springboot_mybatis"/>
				<property name="username" value="root"/>
				<property name="password" value="123456"/>
			</dataSource>
		</environment>
	</environments>
</configuration>
<mappers>
    <mapper class="edu.dj.mapper.UserMapper"/>
</mappers>
  1. 编写接口
public interface UserMapper {
    public List<User> queryUser();
}
  1. 编写Mapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
		PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
		"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="edu.dj.mapper.UserMapper">
	<select id="queryUser" resultType="user">
		select * from springboot_mybatis.user
	</select>
</mapper>
  1. 测试
@Test
public void test() throws IOException {
    String res = "mybatis-config.xml";
    InputStream in = Resources.getResourceAsStream(res);

    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
    SqlSession sqlSession = sqlSessionFactory.openSession(true);

    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    List<User> list = mapper.queryUser();

    for (User user:list){
        System.out.println(user);
    }
}

注意:maven静态资源过滤问题

<build>
    <resources>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.xml</include>
            </includes>
            <filtering>true</filtering>
        </resource>
    </resources>
</build>

9.3 MyBatis-Spring

前期准备:

//pojo层的User类:
import lombok.Data;
@Data
public class User {
    private int id;
    private String userName;
    private String password;
    private String realName;
}

/***********************************************/

//UserMapper接口
public interface UserMapper {
    public List<User> queryUser();
}

/************************************************/

//UserMapperImpl实现类:
public class UserMapperImpl implements UserMapper{

    public void setSessionTemplate(SqlSessionTemplate sessionTemplate) {
        this.sessionTemplate = sessionTemplate;
    }

    //我们的所有操作,在原来,都使用SqlSession来执行,现在都是用SqlSessionTemplate;
    private SqlSessionTemplate sessionTemplate;

    @Override
    public List<User> queryUser() {
        return sessionTemplate.getMapper(UserMapper.class).queryUser();
    }
}

UserMapper.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="edu.dj.mapper.UserMapper">
<select id="queryUser" resultType="user">
        select * from springboot_mybatis.user
</select>
</mapper>
  1. 安装依赖
<dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis-spring</artifactId>
  <version>2.0.6</version>
</dependency>
  1. 配置文件
<!--	DataSource:使用Spring的数据源替换MyBatis的配置 c3p0  dbcp  druid-->
<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/springboot_mybatis?serverTimezone=GMT&amp;useSSL=false"/>
    <property name="username" value="root"/>
    <property name="password" value="123456"/>
</bean>
<!--	sqlSessionFactory-->
<bean class="org.mybatis.spring.SqlSessionFactoryBean" id="sqlSessionFactory">
    <property name="dataSource" ref="dataSource"/>
    <!--		绑定MyBatis配置文件-->
    <property name="configLocation" value="classpath:mybatis-config.xml"/>
    <property name="mapperLocations" value="classpath:edu/dj/mapper/UserMapper.xml"/>
</bean>
<!--	SqlSessionTemplate:就是我们使用的sqlSession-->
<bean class="org.mybatis.spring.SqlSessionTemplate" id="sqlSessionTemplate">
    <constructor-arg ref="sqlSessionFactory"/>
</bean>
<bean id="userMapper" class="edu.dj.mapper.UserMapperImpl">
    <property name="sessionTemplate" ref="sqlSessionTemplate"/>
</bean>
  1. 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="edu.dj.pojo"/>
	</typeAliases>

</configuration>

10 声明式事务

1. 回顾事务

  • 把一组事务当成一个业务来做,要么都成功,要么都失败。
  • 事务在项目开发中十分重要,涉及到数据的一致性。
  • 确保完整性和一致性。

事务的ACID原则:

  • 原子性
  • 一致性
  • 隔离性
    • 多个业务可能操作同一个资源,防止数据损坏
  • 持久性
    • 事务一旦提交,无论系统发生什么问题,结果都不会再被影响,被持久化的写到存储器中!

2.spring中的事务管理

  • 声明式事务:将AOP
<!--	配置声明式事务-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--		<constructor-arg ref="dataSource"/>-->
    <property name="dataSource" ref="dataSource"/>
</bean>
<!--	结合AOP实现事务的织入-->
<!--	配置事务通知-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
    <!--给哪些方法配置事务-->
    <!--配置事务的传播特性,新东西 propagation-->
    <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="txPointCut" expression="execution(* edu.dj.mapper.*.*(..))"/>
    <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
</aop:config>
  • 编程式事务:需要在代码中进行事务的管理
    思考:
    为什么需要事务?
  • 如果不配置事务,可能存在数据提交不一致的情况
  • 如果不在spring中去配置事务声明式事务,就需要在代码中手动配置事务!
  • 事务在项目开发中十分重要,涉及到数据的一致性和完整性问题
posted @ 2021-06-18 11:49  DingJie1024  阅读(52)  评论(0编辑  收藏  举报