Spring重点记录

news2024/9/28 5:34:18

文章目录

  • 1.Spring的组成
  • 2.Spring优点
  • 3.IOC理论推导
  • 4.IOC本质
  • 5.IOC实现:xml或者注解或者自动装配(零配置)。
  • 6.hellospring
    • 6.1beans.xml的结构为:
    • 6.2.Spring容器
    • 6.3对象的创建和控制反转
  • 7.IOC创建对象方式
    • 7.1以有参构造的方式创建对象:
  • 8.spring配置说明
    • 8.1别名
    • 8.2Bean的配置
    • 8.3import
  • 9.依赖注入方式
    • 9.1三种注入方式
    • 9.2.set注入方式(`重点`)
    • 9.3.p命名空间和c命名空间注入:
    • 9.4.bean的作用域:
  • 10.Bean的自动装配
  • 11.注解实现自动装配
    • 11.1 在beans.xml中加入注解支持:
    • 11.2注解实例
    • 11.3@Resource和@Autowired的区别
  • 12.使用注解开发
    • 12.1注解的应用场景
    • 12.2注解说明:
  • 13.使用javaconfig实现配置
    • 13.1配置类实现配置的步骤:
    • 13.2回顾:
  • 14.代理
    • 14.1.静态代理模式:
    • 14.2.动态代理:
    • 14.3代理类ProxyInvocationHandler.java
  • 15.AOP
    • 15.1.什么是AOP?
    • 15.2.使用spring实现AOP
      • 15.2.1方式一:使用原生的Spring API接口
      • 15.2.2方式二:自定义diy类
      • 15.2.3方式三:使用注解方式实现AOP
  • 16.整合Mybatis
    • 1.导入相关jar包:
    • 2.编写配置文件
    • 3.实体类,Mapper及xml文件和实现类
      • 1.UserMapperImpl
      • 2.UserMapperImpl2
  • 17.Spring声明式事务
    • 17.1回顾事务
    • 17.2配置声明式事务
    • 17.3spring中的事务管理


1.Spring的组成

在这里插入图片描述
在这里插入图片描述

2.Spring优点

在这里插入图片描述

3.IOC理论推导

IOC(控制反转):获得依赖对象的方式反转了。
在这里插入图片描述
控制反转后,主动权交给用户了,不在程序员手上了。

4.IOC本质

在这里插入图片描述
在这里插入图片描述
ioc容器把他们解耦了。通过接口的调用就没有原来的强联系了。

5.IOC实现:xml或者注解或者自动装配(零配置)。

在这里插入图片描述

6.hellospring

spring核心配置文件官方名:applicationContext.xml。
这里记为beans.xml。

6.1beans.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-3.0.xsd ">

</beans>

Hello.java

public class Hello {
    public String str;

    public String getStr() {
        return str;
    }

    public void setStr(String str) {
        this.str = str;
    }

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

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
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd ">

<!--使用spring创建对象,在spring中这些都成为bean-->
    <bean id="hello" class="com.kuang.pojo.Hello">
        <property name="str" value="SPRING"/>
    </bean>

</beans>

MyTest测试:

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());
    }
}

6.2.Spring容器

这里的spring容器:
在这里插入图片描述

在这里插入图片描述

6.3对象的创建和控制反转

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

7.IOC创建对象方式

默认走的 无参构造 创建对象。

7.1以有参构造的方式创建对象:

在这里插入图片描述

测试类User.java

public class User {
    private String name;
//public User(){
//    System.out.println("默认构造器");
//}
    public User(String name){
    this.name=name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    public void show(){
        System.out.println("name="+name);
    }
}

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
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd ">
<!--    1.无参构造器创建对象-->
<!--<bean id="user" class="com.kuang.pojo.User">-->
<!--    <property name="name" value="请见"/>-->
<!--</bean>-->
<!--    2.有参构造器通过下标-->
<!--<bean id="user" class="com.kuang.pojo.User">-->
<!--    <constructor-arg index="0" value="123"/>-->
<!--</bean>-->
<!--3.有参构造器通过类型 创建对象,【不推荐使用】-->
<!--    <bean id="user" class="com.kuang.pojo.User">-->
<!--        <constructor-arg type="java.lang.String" value="345"/>-->
<!--    </bean>-->
<!--4.有参构造通过参数名【推荐】-->
    <bean id="user" class="com.kuang.pojo.User">
        <constructor-arg name="name" value="777"/>
    </bean>
  
</beans>

8.spring配置说明

8.1别名

  <alias name="user" alias="user2"/>

8.2Bean的配置

在这里插入图片描述

8.3import

在这里插入图片描述

9.依赖注入方式

9.1三种注入方式

在这里插入图片描述

9.2.set注入方式(重点)

Student:

public class Student {
    private String name;
    private Address address;
    private String[] books;
    private List<String> hobbys;//List<Address>
    private Map<String, String> card;
    private Set<String> games;
    private String wife;
    private Properties info;
    }

Address

public class Address {
    private String address;
}

User

public class User {
    private String name;
    private int age;
}

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
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd ">
<bean id="address" class="com.kuang.pojo.Address">
    <property name="address" value="中安路风华街123号"/>
</bean>
    <bean id="student" class="com.kuang.pojo.Student">
        <property name="name" value="李明"/>
        <property name="address" ref="address"/>
        <property name="books">
            <array>
               <value>十四号书</value>
               <value>传奇书</value>
               <value>史诗书</value>
            </array>
        </property>
        <property name="hobbys" >
            <list>
                <value>足球</value>
                <value>篮球</value>
                <value>羽毛球</value>
            </list>
        </property>
        <property name="card">
            <map>
                <entry key="蓝色" value="大海"/>
                <entry key="金色" value="太阳"/>
                <entry key="黑色" value="夜晚"/>
            </map>
        </property>
        <property name="games">
            <set>
                <value>按此</value>
                <value>阿斯顿</value>
                <value>雪国</value>
            </set>
        </property>
<property name="wife">
    <null/>
</property>
        <property name="info">
            <props>
                <prop key="1">123</prop>
                <prop key="2">456</prop>
                <prop key="3">789</prop>
            </props>
        </property>
    </bean>
</beans>

在这里插入图片描述
在这里插入图片描述

9.3.p命名空间和c命名空间注入:

在这里插入图片描述

9.4.bean的作用域:

在这里插入图片描述

10.Bean的自动装配

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

11.注解实现自动装配

11.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"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd ">
    <!--    指定扫描的包,这个包下的注解就会生效。-->
    <context:component-scan base-package="com.kuang.pojo"/>
    <context:annotation-config/>

</beans>

11.2注解实例

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd ">

<!--    加入注解支持。3个约束,1个标签。-->
<context:annotation-config/>
    <bean id="cat111" class="com.kuang.pojo.Cat"/>
    <bean id="cat11" class="com.kuang.pojo.Cat"/>
    <bean id="dog111" class="com.kuang.pojo.Dog"/>
    <bean id="dog11" class="com.kuang.pojo.Dog"/>
<!--    <bean id="people" class="com.kuang.pojo.People"/>-->
    <bean id="people" class="com.kuang.pojo.People">
        <property name="name" value="奥斯"/>
    </bean>
<!--    虽然在容器中没有写autowired,但是因为在People中对属性使用了@Autowired的注解,也是实现了自动注入。-->
</beans>
public class People {
    private String name;
//    @Autowired按类型自动注入。类型相同时,加入@Qualifier加入ByName方式.
//    表示使用对应bean的对象作为属性注入。
//    @Resource不能指定name,在通过Type和Name都失败的情况下,才会报错。可通过name指定
    @Resource(name = "dog11")
    private Dog dog;
    @Autowired
    @Qualifier(value = "cat11")
    private Cat cat;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Dog getDog() {
        return dog;
    }

    public void setDog(Dog dog) {
        this.dog = dog;
    }

    public Cat getCat() {
        return cat;
    }

    public void setCat(Cat cat) {
        this.cat = cat;
    }

    @Override
    public String toString() {
        return "People{" +
                "name='" + name + '\'' +
                ", dog=" + dog +
                ", cat=" + cat +
                '}';
    }
}

11.3@Resource和@Autowired的区别

在这里插入图片描述

12.使用注解开发

12.1注解的应用场景

在这里插入图片描述
aop包查看是否存在。
在这里插入图片描述

//等价于<bean id="user" class="com.kuang.pojo.User"/>
@Component
@Scope("singleton")
public class User {
//    相当于<property name="name" value="kuangshen"/>
@Value("8888")
    public String name;

}

一些复杂的还是建议走配置文件,比如:

在这里插入图片描述

12.2注解说明:

  • 自动装配的注解:

  • @Autowired:自动装配,通过类型,名字。
    如果名字不唯一: @Qualifier(value = “cat11”)

  • @Nullable:字段标记这个注解,说明这个注解可以为null。

  • @Resource(name = “dog11”):自动装配,通过名字,类型。

  • @Component:组件,说明这个类被spring管理了,作为一个bean。

    • 属性的注入: @Value(“”) :为bean组件注入值。
    • 三个衍生注解:@Controller,@Service,@Repository作用都和@Component一样,只是起一个标识的作用。
    • @Scope() singleton,prototype
      在这里插入图片描述

13.使用javaconfig实现配置

13.1配置类实现配置的步骤:

使用这样一个java配置类等价于配置文件:

package com.kuang.config;

import com.kuang.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 //@Configuration表示这是一个配置类,类似之前的beans.xml
@ComponentScan("com.kuang.pojo")
@Import(MyConfig2.class)
public class MyConfig {

    @Bean
    public User getUser(){
        return new User();
    }
}

User类:

@Component
public class User {
    private String name;

    public String getName() {
        return name;
    }
@Value("萨科理解的")
    public void setName(String name) {
        this.name = name;
    }

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

测试类MyTest.java

import com.kuang.config.MyConfig;
import com.kuang.pojo.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

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

在这里插入图片描述
这种纯java的配置方式,在SpringBoot中随处可见。
注解学习尽量去看源码,是在平时的学习中去养成。

13.2回顾:

1.所有的类都要放到bean里面
2.所有的bean都要通过容器去取
3.容器中的bean取出后就是一个对象。
Mybatis建议用xml去配,因为能够适应复杂的情况。

14.代理

代理模式是SpringAOP的底层【SpringAOP和SpringMVC】
代理模式的分类:

  • 静态代理
  • 动态代理

14.1.静态代理模式:

在这里插入图片描述
程序的一个原则:尽量不去改变原有的代码。
在这里插入图片描述

14.2.动态代理:

在这里插入图片描述
在这里插入图片描述

14.3代理类ProxyInvocationHandler.java

package com.kuang.demo04;

import com.kuang.demo03.Rent;

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 setRent(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+"方法");
    }
}

Client.java

public class Client {
    public static void main(String[] args) {
   		//真实角色
        UserServiceImpl userService = new UserServiceImpl();
        //生成代理角色的类
        ProxyInvocationHandler pih = new ProxyInvocationHandler();
        //通过调用程序处理角色来处理我们要调用的接口对象
        pih.setRent(userService);
        UserService proxy = (UserService) pih.getProxy();
        proxy.add();
    }
}

别人问可以知道有InvocationHandler和Proxy这两个类,

  • InvocationHandler这个类是用于生成动态实例的,通过设置要代理的对象(真实角色),动态生成代理类。
  • InvocationHanler调用处理程序并返回一个结果。
  • Proxy:提供动态代理类的静态方法

在这里插入图片描述

15.AOP

15.1.什么是AOP?

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

15.2.使用spring实现AOP

使用AOP需要导入织入包:

  <!--    使用aop织入,需要导入的包-->
  <dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.4</version>
  </dependency>
</dependencys>

在beans.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
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">


</beans>

15.2.1方式一:使用原生的Spring API接口

定义后置日志:

package com.kuang.log;
import org.springframework.aop.AfterReturningAdvice;
import java.lang.reflect.Method;

public class AfterLog implements AfterReturningAdvice {
    @Override
    public void afterReturning(Object returnValue, Method method, Object[] objects, Object o1) throws Throwable {
        System.out.println("执行了"+method.getName()+"方法,返回结果为:"+returnValue);
    }
}

定义前置日志:

package com.kuang.log;
import org.springframework.aop.MethodBeforeAdvice;
import java.lang.reflect.Method;

public class Log implements MethodBeforeAdvice {

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

在beans.xml中配置:

 <!--     方式一:使用原生的Spring API接口
        配置aop:需要导入aop的约束 -->
<aop:config>
<!--    切入点 expression表达式,execution(要执行的位置(修饰词 返回值 类名 方法名 参数))类.*(..)表示该类下的所有方法带参数-->
    <aop:pointcut id="pointcut" expression="execution(* com.kuang.service.UserServiceImpl.*(..))"/>

<!--    执行环绕增加,即要增加哪个类?切入到哪里?-->
    <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
    <aop:advisor advice-ref="afterlog" pointcut-ref="pointcut"/>
</aop:config>

切入点:在哪个地方去执行方法。
执行UserServiceImpl类的所有方法。两个点代表可以有任意的参数。
aop:advisor:执行环绕增加,即要增加哪个类?切入到哪里?

MyTest测试类:

import com.kuang.service.UserService;
import com.kuang.service.UserServiceImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


public class MyTest {
    public static void main(String[] args) {
        ApplicationContext cpx = new ClassPathXmlApplicationContext("beans.xml");
        UserService userservice = cpx.getBean("userservice", UserService.class);
        userservice.del();
    }
}

15.2.2方式二:自定义diy类

public class DiyPointCut {
    public void before(){
        System.out.println("方法执行前");
    }
    public void after(){
        System.out.println("方法执行后");
    }
}

   <!--  方式二:自定义类 -->
    <bean id="diy" class="com.kuang.diy.DiyPointCut"/>
    <aop:config>
<!--        自定义切面,ref:要引用的类-->
        <aop:aspect ref="diy">
<!--            切入点-->
            <aop:pointcut id="pointcut" expression="execution(* com.kuang.service.UserServiceImpl.*(..))"/>
<!--            通知-->
            <aop:before method="before" pointcut-ref="pointcut"/>
            <aop:after method="after" pointcut-ref="pointcut"/>
        </aop:aspect>
    </aop:config>

15.2.3方式三:使用注解方式实现AOP

package com.kuang.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.kuang.service.UserServiceImpl.*(..))")
    public void before(){
        System.out.println("====方法执行前=====");
    }
@After("execution(* com.kuang.service.UserServiceImpl.*(..))")
    public void after(){
        System.out.println("=====方法执行后=====");
    }
@Around("execution(* com.kuang.service.UserServiceImpl.*(..))")
    public void around(ProceedingJoinPoint jp) throws Throwable {
    System.out.println("环绕前");
    Object proceed = jp.proceed();
    Signature signature = jp.getSignature();//获得签名
    System.out.println("signature:"+signature);
    System.out.println("环绕后");
}

}

在beans.xml中注册并开启注解支持:

<!--    注册注解方式的类-->
    <bean id="annotationPointCut" class="com.kuang.diy.AnnotationPointCut"/>
<!--    开启注解支持-->
    <aop:aspectj-autoproxy/>

16.整合Mybatis

在这里插入图片描述

1.导入相关jar包:

整合Mybatis需要引入依赖:

<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>2.0.2</version>
</dependency>
  <!--        spring操作数据库,还需要一个spring-jdbc-->
<dependency>
     <groupId>org.springframework</groupId>
     <artifactId>spring-jdbc</artifactId>
     <version>5.2.0.RELEASE</version>
 </dependency>

mybatis跟谁整合就-谁就行了
在这里插入图片描述

在这里插入图片描述

2.编写配置文件

2.1引入mybatis核心配置文件: 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核心配置文件-->
<configuration>
    <typeAliases>
        <package name="com.kuang.pojo"/>
    </typeAliases>
    <!--    Environments:多套环境,default可以选择其中一个环境作为默认的环境。-->
<!--    <environments default="development">-->
<!--        <environment id="development">-->
<!--            <transactionManager type="JDBC"/>-->
<!--            <dataSource type="POOLED">-->
<!--                <property name="driver" value="com.mysql.jdbc.Driver"/>-->
<!--                &lt;!&ndash;                在xml文件中,&不能用,需要转义&amp。&ndash;&gt;-->
<!--                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>-->
<!--                <property name="username" value="root"/>-->
<!--                <property name="password" value="123456"/>-->
<!--            </dataSource>-->
<!--        </environment>-->
<!--    </environments>-->

<!--    <mappers>-->
<!--        &lt;!&ndash;  注册xxxMapper.xml文件,  路径以/代替.&ndash;&gt;-->
<!--        <mapper resource="com/kuang/mapper/UserMapper.xml"/>-->
<!--    </mappers>-->

</configuration>

注释的地方由整合后的spring(spring-dao.xml) 实现,mybatis配置文件中这部分的内容可以删掉,一般会留别名和设置(日志开启)mybatis-config.xml文件中。

2.2引入spring整合mybatis的配置文件: 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"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

<!--DataSource:使用Spring的数据源替换Mybatis的配置
 这里使用Spring提供的JDBC,有了数据源,自然要有数据源的属性-->
<bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
    <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    <property name="username" value="root"/>
    <property name="password" value="123456"/>
</bean>

<!--    sqlSessionFactory :通过datasource得到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/kuang/mapper/*.xml"/>
</bean>

<!-- SqlSessionTemplate就是sqlSession  :通过 sqlSessionFactory得到sqlSession-->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<!--    只能使用构造器注入sqlSessionFactory,因为它没有Set方法-->
    <constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
<!--    注入sqlSession-->
    <bean id="userMapper" class="com.kuang.mapper.UserMapperImpl">
        <property name="sqlSession" ref="sqlSession"/>
    </bean>

</beans>

2.3引入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"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<import resource="spring-dao.xml"/>
    <bean id="userMapper" class="com.kuang.mapper.UserMapperImpl">
        <property name="sqlSession" ref="sqlSession"/>
    </bean>
    <bean id="userMapper2" class="com.kuang.mapper.UserMapperImpl2">
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </bean>

</beans>

applicationContext.xml中调userMapper,然后调里面的方法就可以了。 spring-dao.xml以后就用于专注的操作数据库。

3.实体类,Mapper及xml文件和实现类

User

public class User {
    private int id;
    private String name;
    private String pwd;

}

UserMapper

public interface UserMapper {
    public List<User> selectUsers();
}

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">
<!--configuration核心配置文件-->
<mapper namespace="com.kuang.mapper.UserMapper">
    <select id="selectUsers" resultType="user">
        select * from User;
    </select>
</mapper>

两种实现类,选择一种即可

为什么写实现类?
用来替换原来mybatis的操作(原来Mybatis在测试类中实现,现在移到实现类中了)。
两种实现类的区别?
第二中继承了SqlSessionDaoSupport ,里面自带有getSqlSession()方法
两个实现类都做原来mybatis做的事情。

1.UserMapperImpl

package com.kuang.mapper;

import com.kuang.pojo.User;
import org.mybatis.spring.SqlSessionTemplate;

import java.util.List;


public class UserMapperImpl implements UserMapper{
//所有的操作原来都使用sqlSession来执行,现在是SqlSessionTemplate,两者等价。
    private SqlSessionTemplate sqlSession;

    public void setSqlSession(SqlSessionTemplate sqlSession) {
        this.sqlSession = sqlSession;
    }
//原来在测试类中,现在mybatis的操作在这里面
    @Override
    public List<User> selectUsers() {
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        return mapper.selectUsers();
    }
}

注册实现类:

<!--    注入sqlSession-->
    <bean id="userMapper" class="com.kuang.mapper.UserMapperImpl">
        <property name="sqlSession" ref="sqlSession"/>
    </bean>

2.UserMapperImpl2

package com.kuang.mapper;


import com.kuang.pojo.User;
import org.mybatis.spring.support.SqlSessionDaoSupport;

import java.util.List;

public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper{
    @Override
    public List<User> selectUsers() {
     return  getSqlSession().getMapper(UserMapper.class).selectUsers();
    }
}

注册实现类:

<bean id="userMapper2" class="com.kuang.mapper.UserMapperImpl2">
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>

测试:

public class MyTest {

    @Test
    public void tets1() throws IOException {
//        String resource = "mybatis-config.xml";
//        InputStream is = Resources.getResourceAsStream(resource);
//        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
//        SqlSession sqlSession = sqlSessionFactory.openSession(true);
//        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//        List<User> users = mapper.selectUsers();
//        for (User user : users) {
//            System.out.println(user);
//        }
       ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserMapper userMapper = context.getBean("userMapper2", UserMapper.class);
        for (User user : userMapper.selectUsers()) {
            System.out.println(user);
        }
    }
}

在这里插入图片描述

17.Spring声明式事务

17.1回顾事务

在这里插入图片描述
事务的实现:要么改变原来的类,要么横切AOP去实现。
在这里插入图片描述

17.2配置声明式事务

在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"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
    
    </beans>

tx就是事务的缩写。

配置事务:

 <!--    配置声明式事务-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="datasource"/>
    </bean>

    <!--    结合AOP实现事务的织入-->
    <!--    配置事务的通知:-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<!--    给哪些方法配置事务?-->
<!--    配置事务的传播特性:new 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" propagation="REQUIRED"/>
        <tx:method name="*" propagation="REQUIRED"/>
    </tx:attributes>
</tx:advice>

<!--    配置事务切入-->
    <aop:config>
        <aop:pointcut id="txPointCut" expression="execution(* com.kuang.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
    </aop:config>

这些代码是固定的,今后可以直接拿来用,只需要改动execution里面的切入类就可以了。
在这里插入图片描述
了解即可。

17.3spring中的事务管理

在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1486070.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

WPF应用程序使用MVVM模式

文章目录 一、前言二、正文&#xff1a;模式 - WPF应用程序使用MVVM设计模式2.0 一些术语2.1 秩序与混乱2.2 MVVM模式的演变2.3 为何WPF开发者喜爱MVVM2.4 Demo应用程序2.5 路由命令逻辑2.6 ViewModel类层次结构2.7 ViewModelBase类2.8 CommandViewModel类2.9 MainWindowViewMo…

spring注解驱动系列--自动装配

Spring利用依赖注入&#xff08;DI&#xff09;&#xff0c;完成对IOC容器中中各个组件的依赖关系赋值&#xff1b;依赖注入是spring ioc的具体体现&#xff0c;主要是通过各种注解进行属性的自动注入。 一、Autowired&#xff1a;自动注入 一、注解介绍 1、默认优先按照类型去…

MySQL进阶:InnoDB引擎(逻辑存储结构、架构、事务原理、MVCC(面试高频))

&#x1f468;‍&#x1f393;作者简介&#xff1a;一位大四、研0学生&#xff0c;正在努力准备大四暑假的实习 &#x1f30c;上期文章&#xff1a;MySQL进阶&#xff1a;全局锁、表级锁、行级锁总结 &#x1f4da;订阅专栏&#xff1a;MySQL进阶 希望文章对你们有所帮助 MVCC很…

jenkins实战(1)

一, Jenkins官网介绍: Jenkins 持续集成、持续部署 下载地址:Jenkins download and deployment 提供两种类型: LTS(长期版)和Weekly(最近一周的版本) 注: 必须是Java8及以上版本(官网针对这一点有做说明) 二, 安装 下载war包,java -jar XXX --httpPort8081 或 下载war包…

为什么说 TiDB 在线扩容对业务几乎没有影响

本文讨论了分布式数据库在在线扩容方面的挑战&#xff0c; 详细解释了一般分布式数据库和 TiDB 在扩容机制上的不同。 一般分布式数据库在进行在线扩容时&#xff0c;需要重新平衡数据分布&#xff0c;可能会影响系统的可用性和 IO 消耗。 相比之下&#xff0c;TiDB 的存算分离…

五、西瓜书——集成学习

1.个体与集成 集成学习通过将多个学习器进行结合,常可获得比单一学习器显著优越的泛化性能&#xff0c;这对“弱学习器”(weak learner)尤为明显因此集成学习的很多理论研究都是针对弱学习器进行的而基学习器有时也被直接称为弱学习器。 要获得好的集成个体学习器应“好而不同”…

mybatis开发一个分页插件、mybatis实现分页、mybatis拦截器

mybatis开发一个分页插件、mybatis实现分页、mybatis拦截器 通过官网的mybatis插件说明可知&#xff0c;我们可以通过拦截器进行开发一个插件。 例如这样的&#xff1a; UserMapper mapper sqlSession.getMapper(UserMapper.class);// 开始分页MagicPage.startPage(1, 3);//…

八. 实战:CUDA-BEVFusion部署分析-分析BEVFusion中各个ONNX

目录 前言0. 简述1. camera.backbone.onnx(fp16)2. camera.backbone.onnx(int8)3. camera.vtransform.onnx(fp16)4. fuser.onnx(fp16)5. fuser.onnx(int8)6. lidar.backbone.xyz.onnx7. head.bbox.onnx(fp16)总结下载链接参考 前言 自动驾驶之心推出的《CUDA与TensorRT部署实战…

【C++】vector的使用和模拟实现(超级详解!!!!)

文章目录 前言1.vector的介绍及使用1.1 vector的介绍1.2 vector的使用1.2.1 vector的定义1.2.2 vector iterator 的使用1.2.3 vector 空间增长问题1.2.3 vector 增删查改1.2.4 vector 迭代器失效问题。&#xff08;重点!!!!!!&#xff09;1.2.5 vector 在OJ中有关的练习题 2.ve…

蓝桥杯倒计时 41天 - KMP 算法

KMP算法 KMP算法是一种字符串匹配算法&#xff0c;用于匹配模式串P在文本串S中出现的所有位置。 例如S“ababac&#xff0c;P“aba”&#xff0c;那么出现的所有位置是13。 在初学KMP时&#xff0c;我们只需要记住和学会使用模板即可&#xff0c;对其原理只需简单理解&#xff…

WiFi模块引领智能家居革命:连接未来的生活

随着科技的快速发展&#xff0c;智能家居正成为现代生活的一部分&#xff0c;极大地改变了我们与家庭环境互动的方式。其中&#xff0c;WiFi模块作为关键的连接技术&#xff0c;在推动智能家居革命中发挥着不可忽视的作用。本文将深入探讨WiFi模块如何驱动智能家居革命。 设备互…

Maven实战(2)之搭建maven私服

一, 背景: 如果使用国外镜像,下载速度比较慢; 如果使用阿里云镜像,速度还算OK,但是假如网速不好的时候,其实也是比较慢的; 如果没有网的情况下更加下载不了. 二, 本地仓库、个人/公司私服、远程仓库关系如下: 三, 下载安装nexus私服 略

如何在Window系统部署VisualSVN服务并结合cpolar实现无公网ip远程访问

文章目录 前言1. VisualSVN安装与配置2. VisualSVN Server管理界面配置3. 安装cpolar内网穿透3.1 注册账号3.2 下载cpolar客户端3.3 登录cpolar web ui管理界面3.4 创建公网地址 4. 固定公网地址访问 前言 SVN 是 subversion 的缩写&#xff0c;是一个开放源代码的版本控制系统…

Mixtral模型解读

Mixtral 8x7B(Mistral MoE) 1.Mistral 7B模型 Mistral 7B模型与Llama2 7B模型结构整体上是相似的&#xff0c;其结构参数如下所示。 细节上来说&#xff0c;他有两点不同。 1.1SWA(Sliding Window Attention) ​ 一般的Attention来说&#xff0c;是Q与KV-Cache做内积&#…

23端口登录的Telnet命令+传输协议FTP命令

一、23端口登录的Telnet命令 Telnet是传输控制协议/互联网协议&#xff08;TCP/IP&#xff09;网络&#xff08;如Internet&#xff09;的登录和仿真程序&#xff0c;主要用于Internet会话。基本功能是允许用户登录进入远程主机程序。 常用的Telnet命令 Telnet命令的格式为&…

基础算法(四)(递归)

1.递归算法的介绍&#xff1a; 概念&#xff1a;递归是指函数直接或间接调用自身的过程。 解释递归的两个关键要素&#xff1a; 基本情况&#xff08;递归终止条件&#xff09;&#xff1a;递归函数中的一个条件&#xff0c;当满足该条件时&#xff0c;递归终止&#xff0c;避…

C++11中的auto、基于范围的for循环、指针空值nullptr

目录 auto关键字 使用原因 历史背景 C11中的auto auto的使用案例 auto 指针/引用 同一行定义多个变量 typeid关键字 基于范围的for循环 范围for的语法 范围for的使用条件 指针空值nullptr C98中的指针空值 C11中的指针空值 auto关键字 使用原因 随着程序越…

Decoupled Knowledge Distillation解耦知识蒸馏

Decoupled Knowledge Distillation解耦知识蒸馏 现有的蒸馏方法主要是基于从中间层提取深层特征&#xff0c;而忽略了Logit蒸馏的重要性。为了给logit蒸馏研究提供一个新的视角&#xff0c;我们将经典的KD损失重新表述为两部分&#xff0c;即目标类知识蒸馏&#xff08;TCKD&a…

JavaSec 基础之五大不安全组件

文章目录 不安全组件(框架)-Shiro&FastJson&Jackson&XStream&Log4jLog4jShiroJacksonFastJsonXStream 不安全组件(框架)-Shiro&FastJson&Jackson&XStream&Log4j Log4j Apache的一个开源项目&#xff0c;是一个基于Java的日志记录框架。 历史…

python学习笔记------元组

元组的定义 定义元组使用小括号&#xff0c;且使用逗号隔开各个数据&#xff0c;数据是不同的数据类型 定义元组字面量&#xff1a;(元素,元素,元素,......,元素) 例如&#xff1a;(1,"hello") 定义元组变量&#xff1a;变量名称(元素,元素,元素,......,元素)…