spring(idea版)

2023-05-16

spring

文章目录:

  • 1.spring简介
  • 2.IOC推导原型及本质
  • 3.第一个spring程序
  • 4.IOC创建对象的方式
  • 5.spring配置说明
  • 6.Dl依赖注入环境(依赖注入的方式)
  • 7.bean的作用域
  • 8.自动装配bean
  • 9.用注解实现自动装配
  • 10.spring使用注解开发
  • 11.使用java的方式配置spring
  • 12 代理模式
  • 13 使用spring实现AOP
  • 14.整合mybatis
  • 15.Spring声明式事务

1.spring简介

  • 简介
  • 优点
  • 组成

spring简介
在这里插入图片描述

在这里插入图片描述

之后要导入的一些maven依赖
在这里插入图片描述

spring的优点
在这里插入图片描述

在这里插入图片描述

spring组成
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

2.IOC推导原型及本质

  • 推导原型
  • 本质

推导原型

传统的分层模式架构
在这里插入图片描述
在业务层,主要调动dao层的接口实现,

测试类
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
IOC本质

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

3.第一个spring程序

1.导入依赖


	<dependencies>
	        <dependency>
	            <groupId>org.springframework</groupId>
	            <artifactId>spring-webmvc</artifactId>
	            <version>5.2.0.RELEASE</version>
	        </dependency>
			
			<dependency>
		        <groupId>org.springframework</groupId>
		        <artifactId>spring-core</artifactId>
		        <version>5.2.1.RELEASE</version>
    		</dependency>
    		
		    <dependency>
		        <groupId>org.springframework</groupId>
		        <artifactId>spring-beans</artifactId>
		        <version>5.2.1.RELEASE</version>
		    </dependency>
		    
		    <dependency>
		        <groupId>org.springframework</groupId>
		        <artifactId>spring-context</artifactId>
		        <version>5.2.1.RELEASE</version>
		    </dependency>

    
</dependencies>

2.创建实体类

package com.wash.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 + '\'' +
                '}';
    }
}

3.注入bean对象
在resources文件夹下创建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.xsd">
    <!--使用spring来创建对象,在spring这些都称为Bean
        类型 变量名=new 类型();
        Hello hello=new Hello();
        id=变量名
        class:new对象
        property:相当于给对象中的属性赋值

        ref:引用spring容器中创建好的对象
        value:具体的值,基本数据类型
    -->
    <bean id="hello" class="com.wash.pojo.Hello">
        <property name="str" value="spring"/>

    </bean>
</beans>

在这里插入图片描述
4.在测试类中获取bean对象

import com.wash.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());
    }
}


在这里插入图片描述

在这里插入图片描述

之后我们就可以通过这种方式来改变,之前在service层的接口实现方法创建对象,现在直接配置xml文件即可
在这里插入图片描述

4.IOC创建对象的方式

1.使用无参构造创建对象,默认
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

2.使用有参构造创建对象
在这里插入图片描述

  • 1.下标赋值

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

  • 2.通过类型赋值

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

  • 3.直接通过参数名来设置
    在这里插入图片描述
    在这里插入图片描述
    注意:在配置文件加载的时候,spring容器中管理的对象就已经初始化了。

5.spring配置说明

在这里插入图片描述

  • 别名:

在这里插入图片描述

在这里插入图片描述

  • bean

在这里插入图片描述

在这里插入图片描述

  • import

在这里插入图片描述

6.Dl依赖注入环境

依赖注入实际是Set注入

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

第一种:普通值注入,value

 <bean id="hello" class="com.wash.pojo.Hello">
        <property name="str" value="spring"/>

    </bean>

依赖注入的方式:
1.构造器注入:

  • 无参构造
  • 有参构造:
    -下标
    -类型
    -参数名

2.Set方式注入[重点]在这里插入图片描述

  <bean id="a" class="com.wash.pojo.Hello1"/>
   <bean id="hello" class="com.wash.pojo.Hello">
       <!--第一种:普通值注入,value-->
       <property name="str" value="spring"/>
        <!--第二种:bean注入,ref-->
       <property name="adderess" ref="a"/>
       <!--第三种:数组注入,ref-->
       <property name="books">
           <array>
               <value>红楼梦</value>
               <value>西游记</value>
               <value>三国</value>
           </array>
       </property>
       <!--list-->
       <property name="hobbys">
           <list>
               <value>听歌</value>
               <value>敲代码</value>
           </list>
       </property>
       <!--Map-->
       <property name="card">
           <map>
               <entry key="身份证号" value="22134565432"/>
               <entry key="银行卡" value="23455643121"/>
           </map>
       </property>
       <property name="games">
           <set>
               <value>lol</value>
               <value>cf</value>
           </set>
       </property>
       <!--null-->
       <property name="wife">
           <null/>
       </property>
       <property name="info">
           <props>
               <prop key="学号">1706010122</prop>
               <prop key="性别"></prop>
               <prop key="password">19990329</prop>
           </props>
       </property>
    </bean>

在这里插入图片描述

3.其他方式注入

  • p命名空间注入

在这里插入图片描述

在这里插入图片描述

  • c命名空间注入
    在这里插入图片描述
    在这里插入图片描述

7.bean的作用域

在这里插入图片描述
1.单例模式(spring默认机制)

<bean id="hhe" class="com.wash.pojo.Hello" c:str="shuaishuai" scope="singleton"/>

2.原型模式:每次从容器中bean的时候,都会产生一个新对象

  <bean id="hhe" class="com.wash.pojo.Hello" c:str="shuaishuai" scope="prototype"/>

3.其他的request,session,application,这些只能在web开发中使用到。

8.自动装配bean

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

在spring中有三种装配的方式

1.在xml显示的配置

2.在java中显示配置

3.隐式的自动装配bean(重点)

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

9.用注解实现自动装配

jdk1.5支持的注解,spring2.5就支持注解了。

导入约束

<context-annotation-config/>

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

  • @Autowired,直接在实体类的属性上使用即可,也可以在set方法上使用,也可以忽视set方法使用
    省略set方法(使用Autowired我们就可以不用编写set方法了,前提是这个自动装配的属性在IOC容器中存在,且符合名字byname)

  • @如果显示定义了Autowired的required属性为false,说明这个对象为null,否则不允许为空。
    @Autowired(requested=false)

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

  • @Qualifier(value="")

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

  • @resource或@resource(name=“bean的id名”)
    在这里插入图片描述
    在这里插入图片描述

10.spring使用注解开发

  • bean
  • 属性如何注入
  • 衍生的注解
  • 自动装配
  • 作用域

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

1.bean

通过@Component:组件,放在类上,说明这个类被spring管理了,就是bean。

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

2属性如何注入

package com.wash.pojo;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
//等价于  <bean id="user" class="com.wash.pojo.User"/>
@Component
public class User {
    //等价于<property name="name" value="shuai"/>
    @Value("shuai")
    public String name;
}

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

  • dao 【@Repository】
  • service 【@Service】
  • controller 【@Controller】
  • 这四个注解功能是一样的,都是代表将某个类注册到spring中,装配bean

4.自动装配
在这里插入图片描述
5.作用域
在这里插入图片描述

6.xml与注解

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

xml与注解的最佳实践

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

11使用java的方式配置spring

现在完全不使用spring的xml配置了,全权交给Java来做

javaConfig 是spring的一个子项目,在spring4之后,它成为了一个核心功能。

  • 实体类
package com.wash.pojo;

        import org.springframework.beans.factory.annotation.Value;
        import org.springframework.context.annotation.Scope;
        import org.springframework.stereotype.Component;
//等价于  <bean id="user" class="com.wash.pojo.User"/>
@Component
public class User {


    public String name;



    public String getName() {
        return name;
    }
        //等价于<property name="name" value="shuai"/>
    @Value("shuai")
    public void setName(String name) {
        this.name = name;
    }
    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                '}';
    }
}
  • 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.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd">
    <!--指定要扫描的包,这个包下的注解就会生效-->
    <context:component-scan base-package="com.wash.pojo"/>
    <context:annotation-config/>
  • config.java
package com.wash.config;

import com.wash.pojo.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
//这个也会被spring容器托管,因为它本身就是@component,
// @configuration代表这是一个配置类,和beans.xml一样
@ComponentScan("com.wash.pojo")
public class Config {
   //通过方法名获取对象,而@component通过类型小写获取
    //注册一个bean,就相当于写的bean标签,
    //这个方法的名字相当于bean标签的id属性
    //这个方法的返回值,就相当于bean标签的class属性
   @Bean
    public User user(){
        return new User();//就是返回要注入到bean的对象

    }
}
  • 测试类
import com.wash.config.Config;
import com.wash.pojo.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

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

12.代理模式

为什么要学习代理模式?

  • 因为这是spring AOP的底层

12-1 静态代理

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

  • 抽象角色
//租房
public interface Rent {

 public void rent();
}

  • 真实角色
public class Host implements Rent{

    public void rent() {
        System.out.println("房东要租房子");
    }
}
  • 代理角色
public class proxy implements Rent{
    private  Host host;
    public proxy(){}
    public proxy(Host host) {
        this.host = host;
    }
//租房
    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("收中介费");
    }
}

  • 客户端访问代理角色
public class client {
    public static void main(String[] args) {
        Host host = new Host();
        proxy p=new proxy(host);
       //不用面对房东,直接找中介租房即可
        p.rent();
    }
}

在这里插入图片描述

12-2 动态代理

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

  • 代理类

//用这个类来自动生成代理类
public class ProxyInvocationHandler implements InvocationHandler {

   //被代理的接口
   // private Rent rent;
     private Object rent;
    /*public void setRent(Rent rent) {
        this.rent = rent;
    }*/

    public void setRent(Object rent) {
        this.rent = rent;
    }

    //生成得到代理类
    public Object getProxy(){
      return  Proxy.newProxyInstance(this.getClass().getClassLoader(),rent.getClass().getInterfaces(),this);
    }

    //处理代理实例,并返回结果
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
      //动态代理的本质,就是使用反射机制实现
       Object result= method.invoke(rent, args);


        return result;
    }
}
  • 客户端
public class client {
    public static void main(String[] args) {
        //真实角色
        //Host host= new Host();
        serviceimpl service=new serviceimpl();
        //代理角色:现在没有,动态生成
        ProxyInvocationHandler pih= new ProxyInvocationHandler();
        //通过调用程序处理角色来处理我们要调用的接口对象
        pih.setRent(service);//设置要代理的对象
        //动态生成代理类
        Service proxy=(Service) pih.getProxy();
        proxy.add1();
    }
}

一个动态代理类可以代理多个类,只要实现同一个接口即可

13.使用spring实现AOP

  • 方法1:使用spring的API接口【主要springAPI接口实现】
  • 方法2:自定义来实现AOP【主要是切面定义】
  • 方法3:注解实现AOP

使用AOP需要导入一个依赖包

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

在这里插入图片描述

方式1:使用spring的API接口 【主要springAPI接口实现】

  • 1.环境准备
package com.wash.service;

public interface UserService {
    public void add();
    public void delete();
    public void update();
    public void query();

}


public class impl implements UserService{

    public void add() {
        System.out.println("增加");
    }

    public void delete() {
        System.out.println("删除");
    }

    public void update() {
        System.out.println("已修改");
    }

    public void query() {
        System.out.println("已查询");
    }
}
package com.wash.log;


import org.springframework.aop.MethodBeforeAdvice;

import java.lang.reflect.Method;

public class Log implements MethodBeforeAdvice {
//method:要执行的目标对象的方法
//objects:参数
//o:目标对象

    public void before(Method method, Object[] objects, Object o) throws Throwable {
        System.out.println(o.getClass().getName()+"的"+method.getName()+"被执行了");
    }
}

package com.wash.log;

import org.springframework.aop.AfterReturningAdvice;

import java.lang.reflect.Method;

public class Afterlog implements AfterReturningAdvice {
//o:返回值
    public void afterReturning(Object o, Method method, Object[] objects, Object o1) throws Throwable {
        System.out.println("执行了"+method.getName()+"返回结果为"+o);
    }
}

  • 2.bean.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"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd">
  <!--注册bean-->
    <bean id="UserService" class="com.wash.service.impl"/>
    <bean id="log" class="com.wash.log.Log"/>
    <bean id="afterlog" class="com.wash.log.Afterlog"/>
  <!--方式1:使用原生的spring API接口-->
  <!--配置AOP:需要1导入aop的约束-->
    <aop:config>
      <!--首先需要切入点,execution:要执行的位置-->
      <aop:pointcut id="pointcut" expression="execution(* com.wash.service.impl.*(..))"/>
      <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
    </aop:config>
</beans>
  • 3.测试类
import com.wash.service.UserService;
import com.wash.service.impl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.naming.CompositeName;

public class Test001 {
    public static void main(String[] args) {
        ApplicationContext context=new ClassPathXmlApplicationContext("ApplicationComtext.xml");
        //动态代理代理的是接口(注意点)
        UserService userService=(UserService)context.getBean("UserService") ;
      // impl service= context.getBean("UserService", impl.class);
       userService.query();
    }
}

在这里插入图片描述

方法2:自定义来实现AOP【主要是切面定义】

  • 1.环境准备
package com.wash.log;


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

 -

  • 2.bean.xml
 <!--方式2:自定义类-->
  <bean id="diy" class="com.wash.log.DivLog"/>
  <aop:config>
    <!--自定义切面,ref:要引用的类-->
    <aop:aspect ref="diy">
      <!--切入点-->
      <aop:pointcut id="point" expression="execution(* com.wash.service.impl.*(..))"/>
      <!--通知-->
      <aop:before method="before" pointcut-ref="point"/>
      <aop:after method="after" pointcut-ref="point"/>
    </aop:aspect>
  </aop:config>
  • 3.测试类不变

在这里插入图片描述

方法3:注解方式实现AOP

  • 1.java文件
package com.wash.log;

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.Before;

//方法3:使用注解实现AOP
@org.aspectj.lang.annotation.Aspect//标注这个类是一个切面
public class Aspect {

    @Before("execution(* com.wash.service.impl.*(..))")
    public void before1(){
        System.out.println("=======方法执行前======");
    }
    @After("execution(* com.wash.service.impl.*(..))")
    public void after1(){
        System.out.println("=======方法执行后=======");
    }
    @Around("execution(* com.wash.service.impl.*(..))")
    public  void around(ProceedingJoinPoint jp) throws Throwable {
        System.out.println("环绕前");
        //执行方法
        Object proceed= jp.proceed();
        System.out.println("环绕后");
       Signature signature= jp.getSignature();
        System.out.println("signature"+signature);
    }

}

  • 2.bean.xml
 <!--方法3:注解-->
  <bean id="aspect" class="com.wash.log.Aspect"/>
  <!--开启注解支持-->
  <aop:aspectj-autoproxy/>
  • 3.测试类不变

在这里插入图片描述

14.整合mybatis(两种方法)

步骤:

1.导入相关jar包

  • junit
  • mybatis
  • mysql数据库
  • spring相关包
  • aop织入
  • mybatis-spring

maven依赖

<dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.46</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.2</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.1.19.RELEASE</version>
    </dependency>
    <!--spring操作数据库还需要一个spring-jdbc-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>5.1.9.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.8.13</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>2.0.2</version>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.16.10</version>
    </dependency>
</dependencies>

2.编写配置文件

3.测试

mybatis的步骤
在这里插入图片描述

package com.wash.pojo;
//1.编写实体类

import lombok.Data;
@Data
public class User {

    private int id;
    private String ename;
    private String pwd;
}
//2.编写核心配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <typeAliases>
        <package name="com.wash.pojo"/>
    </typeAliases>
    <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/mybatis?serverTimezone=UTC&amp;useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="xiangying216"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper class="com.wash.mapper.Usermapper"/>
    </mappers>
</configuration>
//3.编写接口
package com.wash.mapper;


import com.wash.pojo.User;

import java.util.List;

public interface Usermapper {
    public List<User>selectUser();
}
//4.编写mapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.wash.mapper.Usermapper">
    <select id="selectUser" resultType="user">
       select * from mybatis.user
   </select>
</mapper>
//5.测试
import com.wash.mapper.Usermapper;
import com.wash.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="config.xml";
       InputStream inputStream= Resources.getResourceAsStream(resources);
        SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession=sqlSessionFactory.openSession(true);
        Usermapper usermapper=sqlSession.getMapper(Usermapper.class);
        List<User> userList=usermapper.selectUser();
        for (User user : userList) {
            System.out.println(user);
        }
    }
}

注意:当识别不出mapper.xml时,在pom.xml中添加

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

整合步骤:

  • 编写数据源配置
  • 配置sqlSessionFactory
  • 配置sqlSessionTemplate
  • 需要给接口加实现类
  • 将写的实现类注入到spring里
  • 测试使用
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">
 <!--DataSource使用spring的数据源替换mybatis配置 c3p0,dbcp
 我们这里使用spring提供的 jdbcorg.springframework.jdbc.datasource.DriverManagerDataSource
 -->
 <!--1.编写数据源配置-->
    <bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&amp;useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
        <property name="username" value="root"/>
        <property name="password" value="xiangying216"/>
    </bean>
 <!--2.配置sqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="datasource"/>
        <!--绑定mybatis配置文件-->
        <property name="configLocation" value="classpath:config.xml"/>
        <property name="mapperLocations" value="classpath:com/wash/mapper/*.xml"/>
    </bean>
    <!--SqlSessionTemplate就是我们使用的sqlSession,SqlSessionTemplate
    是Mybatis-Spring的核心它是线程安全的,可以被多个DAO或映射器所共享使用-->
   <!--3.配置SqlSessionTemplate-->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <!--只能使用构造器注入sqlSessionFactory,因为它没有set方法-->
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>
    <!---->
    <bean id="userMapper" class="com.wash.mapper.UserMapperimpl">
        <property name="sqlSession" ref="sqlSession"/>
    </bean>
</beans>
//4.实现类
package com.wash.mapper;

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

import java.util.List;

public class UserMapperimpl implements Usermapper{
//在原来我们的所有操作,都使用sqlSession来执行,现在都使用SqlsessionTemplate
    private SqlSessionTemplate sqlSession;
//为了注册sqlSession,使用set方法
    public void setSqlSession(SqlSessionTemplate sqlSession) {
        this.sqlSession = sqlSession;
    }

    public List<User> selectUser() {
      Usermapper mapper=sqlSession.getMapper(Usermapper.class);
     return mapper.selectUser();
    }
}

<!--5.将写的实现类注入到spring里-->
<bean id="userMapper" class="com.wash.mapper.UserMapperimpl">
        <property name="sqlSession" ref="sqlSession"/>
    </bean>

//6.测试类
import com.wash.mapper.Usermapper;
import com.wash.pojo.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Mytest1 {
    @Test
    public  void test(){
       ApplicationContext context= new ClassPathXmlApplicationContext("spring-dao.xml");
      Usermapper usermapper= context.getBean("userMapper", Usermapper.class);
        for (User user : usermapper.selectUser()) {
            System.out.println(user);
        }
    }

}

注:也可以在applicationcontext.xml导入此xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">
   <import resource="spring-dao.xml"/>
    <bean id="userMapper" class="com.wash.mapper.UserMapperimpl">
        <property name="sqlSession" ref="sqlSession"/>
    </bean>
</beans>

整合mybatis方法2
在方法一的基础上把接口实现类改掉

import com.wash.pojo.User;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.support.SqlSessionDaoSupport;

import java.util.List;

public class UserMapperimpl2 extends SqlSessionDaoSupport implements Usermapper{
//调用getSqlSession()方法就可以得到一个SqlSessionTemplate,之后可以用来执行SQL方法
    public List<User> selectUser() {
//        SqlSession sqlSession=getSqlSession();
//       Usermapper usermapper= sqlSession.getMapper(Usermapper.class);
//        return usermapper.selectUser();
        return getSqlSession().getMapper(Usermapper.class).selectUser();
    }
}

之后在xml中将实现类注入spring,并且属性值不是sqlSession而是sqlSessionFactory

applicationcontext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">
<import resource="spring-dao.xml"/>
<bean id="userMapper" class="com.wash.mapper.UserMapperimpl">
    <property name="sqlSession" ref="sqlSession"/>
</bean>
 <bean id="usermapper2" class="com.wash.mapper.UserMapperimpl2">
     <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
 </bean>
</beans

15.Spring声明式事务

事务
在这里插入图片描述
在这里插入图片描述
spring中的事务管理

  • 声明式事务:AOP
  • 编程式事务:需要在代码中,进行事务的管理
 <!--配置声明式事务-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <constructor-arg ref="datasource"/>
    </bean>
    <!--结合AOP实现事务的织入-->
    <!--配置事务的类:spring帮做了-->
    <!--配置事务通知-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <!--给哪些方法配置支持事务-->
        <tx:attributes>
            <tx:method name="add" propagation="REQUIRED"/>
            <tx:method name="update" propagation="REQUIRED"/>
            <tx:method name="delete" 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(* com.wash.mapper.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txpointcut"/>
    </aop:config>

到这里spring整理完了,之后会整理springMVC的内容

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

spring(idea版) 的相关文章

随机推荐

  • PS照片处理尺寸参考表

    参考表 一 讲多少寸 xff0c 是指长边的英寸数 xff0c 比如5 x 3 5就是5寸 讲多少R xff0c 指短边的英寸数 xff0c 比如4R是6 X 4寸 xff0c 而3R就是5寸的5 X 3 5寸 R 的意思的 rectang
  • 数据库习题及答案5

    模拟测验1 一 1 2 3 4 5 6 7 8 9 10 A D C c D A C A A C 一 选择题 xff08 在每个小题四个备选答案中选出一个正确答案 xff0c 填在题末的括号中 xff09 xff08 本大题共10小题 xf
  • Attention Model(mechanism) 的 套路

    最近刷了一些attention相关的paper 照着here的列表 43 自己搜的paper xff0c 网上相关的资料也有很多 xff0c 在此只讲一讲自己对于attention的理解 xff0c 力求做到简洁明了 一 attention
  • springMVC常用注解

    在java框架中 xff0c 使用注解的作用就是注入属性 一 Spring常用注解 64 Component xff1a 标注一个普通的Spring Bean类 64 Controller xff1a 标注一个控制器组件类 64 Servi
  • Ubuntu16.04运行.sh文件

    前言 xff1a 最近在学 Linux内核分析 xff0c 实验做的是哈工大的oslab Linux 0 11 xff0c 然后下载了相应的压缩包 解压之后发现需要运行setup sh文件 xff0c 原先以为是因为没有切换到root命令所
  • 服务器conda,pip命令用不了解决方法

    服务器创建用户后 xff0c 不知道为啥基本命令可以用 xff0c 但是conda xff0c pip等不能使用 xff0c 度娘后一行命令解决 xff0c 命令如下 source span class token operator spa
  • Base64资源

    Base64资源 在线转Base64工具 http www jsons cn img2base64 鲸鱼 maskImage src 61 39 data image png base64 iVBORw0KGgoAAAANSUhEUgAAA
  • Linux驱动开发

    本文为一个简单的字符设备驱动 xff0c 涉及驱动编写 测试程序编写 Makefile编写 驱动加载 卸载 xff0c 运行于Linux虚拟机 xff0c 不涉及底层配置 撰写本文的主要目的为记录一下驱动的开发流程 xff0c 参考了正点原
  • SpringBoot MVC配置

    SpringBoot MVC配置 在使用 SpringBoot 进行实际的项目开发前 xff0c 最后再了解一下 SpringBoot 中对于 MVC 的配置 xff01 仍对应 SpringBoot 03 Web 项目 1 MVC配置简介
  • Python常用的运算符

    1 算术运算符 xff1a 43 xff1a 加法 xff1a 减法 xff1a 乘法 xff1a 除法 xff1a 求两个数的余数 例如 xff1a 10 3 输出为1 xff1a 整除 例如 xff1a 10 3 输出为3 xff1a
  • npm报错 TypeError [ERR_INVALID_ARG_TYPE]: The “path“ argument must be of type string.Received undefine

    npm报错 TypeError ERR INVALID ARG TYPE The path argument must be of type string Received undefined 解决办法 xff1a 1 修改static文件
  • 持之以恒(一)位姿转换:姿态 / 四元数 / 旋转矩阵 / 欧拉角 及 位姿矩阵

    文章目录 1 简介1 1 位姿的几种表示形式1 2 姿态转换在线工具 2 位姿转换接口2 1 旋转向量 转 四元数2 2 四元数 转 旋转向量2 3 四元数 与 旋转矩阵 3 机器人相关应用3 1 不同厂家协作机器人的位姿表示形式 1 简介
  • 在pgsql中利用regexp_matches提取出正则并且用, 分隔开。

    在pgsql中利用regexp matches提取出正则并且用 xff0c 分隔开 span class token keyword SELECT span string agg span class token punctuation s
  • 推荐系统经典论文文献及业界应用

    Survey方面的文章及资料 Adomavicius G Tuzhilin A Toward the next generation of recommender systems A survey of the state of the a
  • TIOBE 编程语言排行,各个语言优缺点,以及你适合那种编程语言

    TIOBE 编程语言排行前10中 xff0c 各个编程语言的优缺点如下 xff1a Python 优点 xff1a 易学易用 xff0c 具有大量的第三方库和工具支持 xff0c 适用于数据分析 人工智能等领域 缺点 xff1a 运行速度相
  • ssh整合

    ssh整合 思路pom依赖几大框架的配置文件配置struts xml测试 思路 SSH是 struts 43 spring 43 hibernate的一个集成框架 1 导入所需要的pom依赖 2 几大框架的配置文件 xff08 web xm
  • JavaFX程序入门

    JavaFX程序入门 一 JavaFX基本概念 JavaFX的图形用户界面 xff08 GUI xff09 通常称为场景图 xff0c 场景图是构建JavaFX应用程序的起点 场景图除了包括布局面板 UI控件 图像 媒体 图表等 xff0c
  • 二叉树4:二叉树求树高度(超级详细)

    一 思路 什么是树高 xff1f 树的高度 或深度 就是树中结点的最大层数 在这里使用后序遍历的递归算法 对每一个结点都进行如下操作 xff1a 后序遍历其左子树求树高后序遍历其右子树求树高对这个结点进行下面操作 xff1a 比较其左右子树
  • lottie.js动画的使用(JSON动画)

    在public文件中引入lottie js data json 对应图片 1 引入lottie lt script src 61 34 lottie js 34 gt lt script gt 2 页面引入代码 lt div id 61 3
  • spring(idea版)

    spring 文章目录 xff1a 1 spring简介2 IOC推导原型及本质3 第一个spring程序4 IOC创建对象的方式5 spring配置说明6 Dl依赖注入环境 依赖注入的方式 7 bean的作用域8 自动装配bean9 用注