首页 > 其他分享 >spring学习笔记

spring学习笔记

时间:2023-03-04 15:45:52浏览次数:37  
标签:spring void 笔记 学习 context import org public

Spring学习笔记

官方下载地址 : https://repo.spring.io/libs-release-local/org/springframework/spring/

GitHub : https://github.com/spring-projects

<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.2.0.RELEASE</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.2.0.RELEASE</version>
</dependency>

spring 是一个免费的开源的框架 (容器)

spring 是一个轻量级 ,非入侵式的框架

控制反转,面向切面(AOP)

支持事务处理,对框架整合的支持

Spring七大模块

b6e402e2d2984775b36a69765a9d72c7

Spring Boot

​ 快速开发脚手架

​ 基于SpringBoot可以快速开发的小模块

Spring Cloud

基于SpringBoot实现

IOC理论推导

1.UserDao接口

2.UserDaoimpl实现类

3.UserService业务接口

4.UserServiceimpl业务实现类

使用set接口

private UserDao userDao ;

//利用set进行动态实现值的注入
public void setUserDao(UserDao userDao) {
     this.userDao = userDao;
}

之前 是主动创建对象,控制权在程序员

利用set注入之后,程序没有主动性,而是变成被动接受

不用管理对象的创建 , 系统的耦合性增加,提高业务的实现

控制反转IoC(Inversion of Control),是一种设计思想,DI(依赖注入)是实现IoC的一种方法,也有人认为DI只是IoC的另一种说法。没有IoC的程序中 , 我们使用面向对象编程 , 对象的创建与对象间的依赖关系完全硬编码在程序中,对象的创建由程序自己控制,控制反转后将对象的创建转移给第三方,个人认为所谓控制反转就是:获得依赖对象的方式反转了。

控制反转是一种通过描述(XML或注解)并通过第三方去生产或获取特定对象的方式。在Spring中实现控制反转的是IoC容器,其实现方法是依赖注入(Dependency Injection,DI)。

<?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="accountDao"
        class="org.springframework.samples.jpetstore.dao.jpa.JpaAccountDao">
        <!-- additional collaborators and configuration for this bean go here -->
    </bean>

    <bean id="itemDao" class="org.springframework.samples.jpetstore.dao.jpa.JpaItemDao">
        <!-- additional collaborators and configuration for this bean go here -->
    </bean>

    <!-- more bean definitions for data access objects go here -->

</beans>
ApplicationContext context = new GenericGroovyApplicationContext("services.groovy", "daos.groovy");
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">
    <!--bean就是java对象 , 由Spring创建和管理-->
   <!-- 使用spring来创建对象,在spring中都称为bean

         类型 变量名 = new 类型();
         Hello hello = new hello();

         id = 变量名
         class = new 的对象
         property相当于给对象的属性设置一个值
  
   -->

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

    </bean>

IOC由主动的编程变成被动的接收

在xml文件中进行修改

 //获取ApplicationContext对象 , 拿到spring容器
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        // 直接获取
        UserServiceImpl userServiceImpl = (UserServiceImpl) context.getBean("UserServiceImpl");

        userServiceImpl.getUser();

IOC创建对象的方式

1.默认使用无参构造方法

2.正常创建对象,使用有参构造方法

<bean id="exampleBean" class="examples.ExampleBean">
    <constructor-arg name="years" value="7500000"/>
    <constructor-arg name="ultimateAnswer" value="42"/>
</bean>
<bean id="exampleBean" class="examples.ExampleBean">
    <constructor-arg index="0" value="7500000"/>
    <constructor-arg index="1" value="42"/>
</bean>
<bean id="exampleBean" class="examples.ExampleBean">
    <constructor-arg type="int" value="7500000"/>
    <constructor-arg type="java.lang.String" value="42"/>
</bean>
<beans>
    <bean id="beanOne" class="x.y.ThingOne">
        <constructor-arg ref="beanTwo"/>
        <constructor-arg ref="beanThree"/>
    </bean>

    <bean id="beanTwo" class="x.y.ThingTwo"/>

    <bean id="beanThree" class="x.y.ThingThree"/>
</beans>

Spring的配置

别名

    <!--别名-->
    <alias name="User" alias="fuck"/>

bean的配置

  <!--
        id : bean的唯一标识符  相当于对象名
        class  bean对象的全限定名 : 包名加类型
        name : 别名 , 而且name可以去多个name
    -->

    <bean id="UserT" class="com.spring.pojo.UserT" name="userT u u1,u2;u4">
        <property name="name" value="lll"/>
    </bean>

import

一般用于团队开发
applicationcontext.xml
 <import resource="bean1.xml"/>
    <import resource="bean2.xml"/>
    <import resource="beans.xml"/>

DI依赖注入

构造器注入

Set方式注入

​ 依赖注入

​ 依赖 bean对象的创建依赖于容器

​ 注入 bean中的所有属性,由容器来注入

其他方式

完善注册信息


    <bean id="address" class="com.spring.pojo.Address">
        <property name="address" value="spring"/>
     </bean>

    <bean id="student" class="com.spring.pojo.Student">
        <!--第一种-->
        <property name="name" value="spring" />
        <!--第二种 bean注入 ref-->
        <property name="address" ref="address"/>
        <!--数组注入-->
        <property name="books">
            <array>
                <value>红楼梦</value>
                <value>西游记</value>
                <value>水浒传</value>
                <value>三国演义</value>
            </array>
        </property>
        <!--list-->
        <property name="hobbys">

            <list>
                <value>lie</value>
                <value>watch</value>
                <value>pve</value>
            </list>
        </property>

        <!--Map-->
        <property name="card">
            <map>
                <entry key="abc" value="123"></entry>
                <entry key="abcd" value="12323"></entry>
            </map>
        </property>

        <!--set-->
        <property name="games">
            <set>
                <value>lolo</value>
                <value>bobo</value>
                <value>coco</value>
            </set>
        </property>
        <!--null-->
        <property name="wife">
            <null/>
        </property>
        <!--properties
          key = value
          key1 = value
          ......
        -->
        <property name="info">
            <props>
                <prop key="id">114514</prop>

            </props>
        </property>

    </bean>


测试类


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

    }
}




拓展方式注入

使用c命名空间 或者 p命名空间 进行注入
xmlns:c="http://www.springframework.org/schema/c"

xmlns:p="http://www.springframework.org/schema/p"
    @Test
    public void test2(){
        ApplicationContext context = new ClassPathXmlApplicationContext("userbeans.xml");
        User user = context.getBean("user2" , User.class);
        System.out.println(user);
    }

使用 空间时需要导入约束

bean的作用域

![屏幕截图 2023-02-20 231212](C:\Users\lenovo\Desktop\一些东西\spring\屏幕截图 2023-02-20 231212.png)

单例机制 : spring默认的机制

<bean id="user2" class="com.spring.pojo.User" c:name="wrsama" c:age="20" scope="singleton"  />

原型机制:会默认生成一个新的对象

<bean id="user2" class="com.spring.pojo.User" c:name="wrsama" c:age="20" scope="prototype"  />

其他只能在web开发中使用

bean 的自动装配

自动装配是Spring满足bean依赖的一种方式

spring会在上下文中自动寻找,并自动给bean装属性

​ 在xml显示配置

​ 在java中显示配置

​ 隐式 的自动装配bean !

环境搭配

一个人两个宠物

byName自动装配 byType自动装配

    <bean id="people" class="com.spring.pojo.People" autowire="byName">
        <property name="name" value="wrsama"/>
    </bean>
  <bean id="people" class="com.spring.pojo.People" autowire="byType">
        <property name="name" value="wrsama"/>
    </bean>

​ byname : 保证所有bean的id唯一,并且bean需要和自动自动注入的属性的set方法值一致

​ bytype : 保证所有bean的class唯一,并且bean需要和自动自动注入的属性的set方法值一致

使用注解实现自动装配

jdk 1.5开始的注解开发 spring 从2.5

The introduction of annotation-based configuration raised the question of whether this approach is “better” than XML.

使用注解须知

​ 导入约束 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>
<?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
       http://www.springframework.org/schema/aop
       https://www.springframework.org/schema/context/spring-aop.xsd">
       <context:annotation-config/>

</beans>

使用注解开发后

@Autowired

可以直接作用于set()

可以省略掉 set(),但是必须要使自动装配的属性在IOC容器中 (Spring)

byname的方式	
public class People {

    //如果显示的定义的Autowired的required属性为false,说明这个对象可以为null,否则不允许为空
    @Autowired(required = false)
    private Cat cat ;
    @Autowired
    private Dog dog ;
    private String name ;
}																																			
@Nullable 字段标记了的这个注解,可以让这个字段为null
如果@Autowired的环境过于复杂,可以使用@Qualifier(value="xxx")去配置使用		
 	@Autowired
    @Qualifier(value = "dogss")
    private Dog dog ;
    private String name ;
import javax.annotation.Resource

@Resource注解

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

区别

都是自动装配用	, 可以放在字段上

@Autowired 使用的是byType   要求控制对象存在

@Resource 使用byName 或者是 byType  ,如果两种都找不到就会报错

执行顺序不同 :默认条件不同

使用注解开发

在spring4 之后 需要导入AOP包

在使用注解需要导入context约束,增加注解

@Component


Component 的衍生注解


dao层 的@Repository


service  @Service


controller @Controller



使用注解开发,需要对齐jdk和spring的版本关系
@Value 的注入值
public class User {
    @Value("sharuanidea")
    public String name;
}

@scope()

prototype
singleton


在使用注解的时候需要,导入注解 的支持,引入注解扫描

<context:component-scan base-package="com.spring"/>

使用Java来配置spring对象

JavaConfig

spring4之后的核心功能

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class User {

    public String name;

    public String getName() {
        return name;
    }

    @Value("fuck")
    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                '}';
    }
}
import com.spring.pojo.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;




@Configuration
@ComponentScan("com.spring.pojo")
public class SpringConfig {

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

静态代理

​ 抽象角色 : 一般使用抽象类对象或者接口

​ 真实对象:被代理的角色

​ 代理角色:代理真实角色,会进行附属操作

​ 客户:访问被代理的人

设置接口

public interface Rent {
    public void rent();

}

真实角色

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

代理角色

package com.spring.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();
        fare();
        hetong();
    }
    public void seehouse(){
        System.out.println("中介看房");
    }
    public void fare(){
        System.out.println("收费");
    }
    public void hetong(){
        System.out.println("合同");
    }
}

客户层

package com.spring.demo01;

public class Client {
    public static void main(String[] args) {
        Host host = new Host();
        Proxy proxy = new Proxy(host);
        proxy.rent();
        
    }
}

动态代理

动态代理和静态代理的角色是一样的

动态代理的代理类是动态生成的,

动态代理分为两大类 基于接口的动态代理 ,基于类的动态代理

​ 基于接口 JDK的动态代理

​ 基于类的 cglib

​ Java 的 字节码实现 javassist

代理的两个类

Proxy invocationHandler

package com.spring.demo04;



import org.jetbrains.annotations.NotNull;

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 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, @NotNull 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.spring.demo04;

import com.spring.demo02.UserService;
import com.spring.demo02.UserServiceImpl;
import com.spring.demo04.ProxyInvocationHandler;
import java.lang.reflect.InvocationHandler;

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

面向切面编程 AOP

横切关注点

切面 ASPECT

通知Advice

目标 Target

代理Proxy

切入点PointCut

连接点JointPoint

![屏幕截图 2023-03-01 143737](C:\Users\lenovo\Desktop\一些东西\spring\屏幕截图 2023-03-01 143737.png)

使用spring来实现AOP

使用aop织入,导入依赖包

<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.4</version>
</dependency>

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd">
</beans>   
import com.spring.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public  class Mytest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService = (UserService) context.getBean("userService") ;
        userService.add();
    }
}

<?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.spring.service.UserServiceImpl"/>
    <bean id="log" class="com.spring.Log.Log"/>
    <bean id="afterLog" class="com.spring.Log.AfterLog"/>



    <!--方式一 使用原生spring api接口-->
    <!--aop的配置-->
     <aop:config>
        <!--切入点-->
        <!--切入点:expression:表达式 execution(执行的位置)   -->
        <aop:pointcut id="poincut"  expression="execution(* com.spring.service.UserServiceImpl.*(..))"/>

        <!--执行环绕增加-->
        <aop:advisor advice-ref="log" pointcut-ref="poincut"/>
        <aop:advisor advice-ref="afterLog" pointcut-ref="poincut"/>

    </aop:config>

</beans>



使用自定义类来实现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.spring.service.UserServiceImpl"/>
    <bean id="log" class="com.spring.Log.Log"/>
    <bean id="afterLog" class="com.spring.Log.AfterLog"/>
    
    
<!--    自定义类的方法-->
        <bean id="diy" class="com.spring.diy.DiyPointCut"/>
        <!--方式二 自定义切面-->
        <aop:config >
            <!--自定义切面-->
            <aop:aspect ref="diy">
                <!--切入点-->
                <aop:pointcut id="point" expression="execution(* com.spring.service.UserServiceImpl.*(..))"/>

                <!--通知-->
                <aop:before method="before" pointcut-ref="point"/>
                <aop:after method="after" pointcut-ref="point"/>
                
            </aop:aspect>
        </aop:config>

    
</beans>



注解实现 AOP

package com.spring.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.spring.service.UserServiceImpl.*(..))")
    public void before(){
        System.out.println("=======方法执行前======");
    }



    @After("execution(* com.spring.service.UserServiceImpl.*(..))")
    public void after(){
        System.out.println("=======方法执行后=======");
    }


    //在环绕增强中,我们可以给定一个参数,代表我们要处理切入的点
    @Around("execution(* com.spring.service.UserServiceImpl.*(..))")
    public void around(ProceedingJoinPoint jp) throws Throwable {
        System.out.println("环绕前");


        Signature signature = jp.getSignature(); //获得签名
        System.out.println("signature:"+signature);

        //执行方法
        Object proceed = jp.proceed();

        //环绕后
        System.out.println("环绕后");

        System.out.println(proceed);
    }





}

        <!--方式3-->
        <bean id="annotationPointCut" class="com.spring.diy.AnnotationPointCut"/>
        <!--开启注解支持-->

        <!--开启注解支持     jdk(默认 proxy-target-class="false") cglib(proxy-target-class="true")-->
        <aop:aspectj-autoproxy proxy-target-class="false"/>

整合Mybatis

导入相关jar包

​ junit

​ mybatis

​ mysql相关

​ spring相关的

​ aop织入

​ mybatis-spring

    <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.47</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.2.0.RELEASE</version>
        </dependency>
<!--        spring操作数据库还需要使用spring-jdbc-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.2.0.RELEASE</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.4</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
        <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>



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

编写配置文件

测试

Mybatis操作

编写实体类

编写核心配置文件

编写接口

编写Mapper.xml

测试

Mybatis-Spring

编写数据源

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       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的配置   c3p0 dbcp druid
        使用spring内置的jdbc :jdbc
    -->

    <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?useSSL=false&amp;useUnicode=false&amp;characterEncoding=UTF-8"/>
            <property name="username" value="root"/>
            <property name="password" value="13140284966wr"/>
    </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/spring/mapper/*.xml"/>

    </bean>

    <!--SqlSessionTemplate  为mybatis中的 sqlsession   -->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <!--只能使用构造器注入sqlSessionFactory , 因为这个没有set方法-->
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>
    <bean id="userMapper" class="com.spring.mapper.UserMapperImpl">
        <property name="sqlSession" ref="sqlSession"/>
    </bean>

</beans>



package com.spring.mapper;

import com.spring.pojo.User;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionTemplate;

import java.util.List;

public class UserMapperImpl implements UserMapper{

    //操作使用sqlsession来实现
    private SqlSessionTemplate sqlSession;

    public void setSqlSession(SqlSessionTemplate sqlSession) {
        this.sqlSession = sqlSession;
    }

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

编写一个总的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">

    <import resource="spring-dao.xml"/>


    <bean id="userMapper" class="com.spring.mapper.UserMapperImpl">
        <property name="sqlSession" ref="sqlSession"/>
    </bean>
</beans>



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"
       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的配置   c3p0 dbcp druid
        使用spring内置的jdbc :jdbc
    -->

    <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?useSSL=false&amp;useUnicode=false&amp;characterEncoding=UTF-8"/>
            <property name="username" value="root"/>
            <property name="password" value="13140284966wr"/>
    </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/spring/mapper/*.xml"/>

    </bean>

    <!--SqlSessionTemplate  为mybatis中的 sqlsession   -->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <!--只能使用构造器注入sqlSessionFactory , 因为这个没有set方法-->
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>
    <bean id="userMapper" class="com.spring.mapper.UserMapperImpl2">
        <property name="sqlSession" ref="sqlSession"/>
    </bean>

    <!--声明式事务-->
<!--    <bean id="transactionManger" class="org.springframework.jdbc.datasource.DriverManagerDataSource">-->
<!--        <property name="dataSource" ref="dataSource"/>-->
<!--    </bean>-->
    <!--AOP实现事务的织入-->
    <tx:advice id="txAdivice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="add" propagation="REQUIRED"/>
            <tx:method name="delete" propagation="REQUIRED"/>
            <tx:method name="update" propagation="REQUIRED"/>
            <tx:method name="query" read-only="true"/>
            <tx:method name="*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>


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

</beans>



标签:spring,void,笔记,学习,context,import,org,public
From: https://www.cnblogs.com/Rsama/p/1st.html

相关文章

  • AWS学习之路(二)
    IAM:Users&GroupsIAM=IdentityandAccessManagement,GlobalserviceRootaccountcreatedbydefault,shouldn`t`beusedorsharedUsersarepeoplewithinyo......
  • SSM框架-Spring学习日记7
    声明式事务事务在项目开发过程非常重要,涉及到数据的一致性的问题,不容马虎!事务管理是企业级应用程序开发中必备技术,用来确保数据的完整性和一致性。事务就是把一系列的动......
  • es学习
    1.es常见知识点1.1es索引操作创建索引:PUT/es_db创建索引时可以设置分片数和副本数:PUT/es_db2{"settings":{"number_of_shards":1,"number_of_r......
  • SSM框架-Spring学习日记6
    Spring整合MyBatis1.导入相关jar包junit<dependency>  <groupId>junit</groupId>  <artifactId>junit</artifactId>  <version>4.12</version></dependenc......
  • numpy深度学习常用函数及参数理解(axis, keepdims)
    axis:以axis=0为例,则沿着第0个下标(最左边的下标)变化的方向进行操作,也就是将除了第0个下标外,其他两个下标都相同的部分分成一组,然后再进行操作例如一个3*3的二维数组A(3,......
  • 第二三周学习总结
    第二周明显有所懈怠,靡不有初,鲜克有终。坚持,努力。这两周还在爬虫,学习了urllib库,bs4模块,re库,分别是伪装浏览器,解析数据,字符串规则,目前还差保存数据模块,即xlwt库,等学完就把......
  • SSM框架-Spring学习日记5
    什么是AOPAOP(AspectOrientedProgramming)意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。AOP是OOP的延续,是软件开发中的一个热点,也......
  • SpringMVC:各个响应中的数据流转如何实现?
    依赖request、session、application对象进行数据流转。 一、普通流转直接从三大对象(request、session、application)中存入、取出数据。例子:此响应器会把数......
  • spring声明式事务提交工具类
    packagecom.talkweb.modou;importorg.slf4j.Logger;importorg.slf4j.LoggerFactory;importorg.springframework.beans.factory.annotation.Autowired;importorg.......
  • 【Spring Boot源码剖析之Spring Boot源码剖析】
    SpringBoot源码剖析SpringBoot依赖管理问题:(1)为什么导入dependency时不需要指定版本?SpringBoot项目的父项目依赖spring-boot-starter-parent<parent><groupId>org.......