Spring框架详解(了解IOC,AOP)


一、spring入门

1.理解IOC

  • IOC是Inversion of Control的缩写,多数书籍翻译成“控制反转”。
  • IOC理论提出的观点大体是这样的:借助于“第三方”实现具有依赖关系的对象之间的解耦。

我们知道在面向对象设计的软件系统中,它的底层都是由N个对象构成的,各个对象之间通过相互合作,最终实现系统地业务逻辑。
在这里插入图片描述

大家看到了吧,由于引进了中间位置的“第三方”,也就是IOC容器,使得A、B、C、D这4个对象没有了耦合关系,齿轮之间的传动全部依靠“第三方”了,全部对象的控制权全部上缴给“第三方”IOC容器,所以,IOC容器成了整个系统的关键核心,
在这里插入图片描述

把上图中间的IOC容器拿掉,然后再来看看这套系统:我们现在看到的画面,就是我们要实现整个系统所需要完成的全部内容。这时候,A、B、C、D这4个对象之间已经没有了耦合关系,彼此毫无联系,这样的话,当你在实现A的时候,根本无须再去考虑B、C和D了,对象之间的依赖关系已经降低到了最低程度。
在这里插入图片描述

软件系统在没有引入IOC容器之前,如图1所示,对象A依赖于对象B,那么对象A在初始化或者运行到某一点的时候,自己必须主动去创建对象B或者使用已经创建的对象B。无论是创建还是使用对象B,控制权都在自己手上。通过前后的对比,我们不难看出来:对象A获得依赖对象B的过程,由主动行为变为了被动行为,控制权颠倒过来了,这就是“控制反转”这个名称的由来。

2.导入依赖

<dependencies>
        <!--WebMvc-->
        <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.3.10</version>
        </dependency>
    </dependencies>

3.核心配置文件

<?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">

4.spring容器创建对象之无参构造法

无参构造法:

在实体类中写一个无参构造,并做出标记。

public class Hello {
    
    
    private String name;
    private int age;

    public Hello() {
    
    
        System.out.println("这是无参构造");
    }

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

    public void setAge(int age) {
    
    
        this.age = age;
    }

}

注入bean:

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

测试:

public class MyTest {
    
    
    public static void main(String[] args) {
    
    
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        Hello hello = (Hello) context.getBean("hello");
        // hello.show();
    }
}

结果:
在这里插入图片描述
无参构造注意事项:

  • 使用property注入
  • 必须要有set方法**

5.spring容器创建对象之有参构造法

实体类:

public class People {
    
    
    private String name;
    private int age;

    public People(String name, int age) {
    
    
        this.name = name;
        this.age = age;
        System.out.println("people");
    }

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

    public void setAge(int age) {
    
    
        this.age = age;
    }
    public void show(){
    
    
        System.out.println("name+"+name);
    }

}

注入bean:


    <bean id="hello2" class="com.rcy.pojo.People">
        <constructor-arg name="age" value="20"/>
        <constructor-arg name="name" value="lala"/>
    </bean>

测试:

在这里插入图片描述
有参构造注意事项:

  • 使用constructor来注入
  • 可以使用name=也可以使用index=,后者指的是实体类中的第几个属性。

二、spring配置

1.别名

<bean id="hello2" class="com.rcy.pojo.People" name="c,a,v p">
        <constructor-arg name="age" value="20"/>
        <constructor-arg name="name" value="lala"/>
    </bean>
    <alias name="hello2" alias="dududu"/>

有两种起别名方法:
使用"alias"标签起别名
使用name起别名,使用name可以起多个别名,中间可以用逗号分号空格分开。

2.bean的配置

<!--    id:bean的唯一标识
        class:bean的全限定名称包名加类型
 -->
    <bean id="hello2" class="com.rcy.pojo.People" name="c,a,v p">
        <constructor-arg name="age" value="20"/>
        <constructor-arg name="name" value="lala"/>

3.import

import一般用于团队开发,可以将多个bean.xml文件合并为一个applicationContext.xml。

三、依赖注入

1.set方式注入

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

Student实体类

public class Student {
    
    

        private String name;
        private Adress adress;
        private String[]book;
        private List<String>hobbys;
        private Map<String,String> card;
        private Set<String> games;
        private String wife;
        private Properties info;

Adress实体类,作为Student的引用对象。

public class Adress {
    
    
    private String Adress;
}

applicationContext.xml文件,里面有各种不同类型的注入方法

<bean id="adress" class="com.rcy.pojo.Adress">
        <property name="adress" value="西安"/>
    </bean>
    <bean id="student" class="com.rcy.pojo.Student">
        <!-- 第一种,普通注入value-->
        <property name="name" value="董瑞龙"/>

        <!-- 第二种,bean注入ref-->
        <property name="adress" ref="adress"/>

        <!-- 第三种,数组注入-->
        <property name="book">
            <array>
                <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="610121214566"/>
                <entry key="学号" value="1401541"/>
            </map>
        </property>

        <!--第六种Set-->
        <property name="games">
            <set>
                <value>LOL</value>
                <value>王者</value>
            </set>
        </property>

        <!--第七种null-->
        <property name="wife">
            <null/>
        </property>

        <!--第八种properties-->
        <property name="info">
            <props>
                <prop key="url"></prop>
                <prop key="班级">2班</prop>
            </props>
        </property>

    </bean>

2.拓展注入方式

2.1 p命名方式

加入p约束:xmlns:p=“http://www.springframework.org/schema/p”

实体类:

public class Hello {
    
    
    private String name;
    private int age;

    public Hello() {
    
    
    }

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

    public void setAge(int age) {
    
    
        this.age = age;
    }

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

p命名方式注入方法:

  <bean id="hello" class="com.rcy.pojo.Hello" scope="singleton" p:name="lige" p:age="12">
    </bean>

测试类:

public void test3(){
    
    
            ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
            Hello student = (Hello) context.getBean("hello");
            System.out.println(student);
        }

结果:
在这里插入图片描述

2.2c命名方式

加入c约束:xmlns:c=“http://www.springframework.org/schema/c”

实体类:

public class People {
    
    
    private String name;
    private int age;

    public People(String name, int age) {
    
    
        this.name = name;
        this.age = age;
    }

    public void setName(String name) {
    
    
        this.name = name;
    }
    public void setAge(int age) {
    
    
        this.age = age;
    }
    @Override
    public String toString() {
    
    
        return "People{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

c命名方式注入方法:

<bean id="people" class="com.rcy.pojo.People" c:name="张龙飞" c:age="20">
    </bean>

测试类:

public void test4(){
    
    
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        People people= (People) context.getBean("people");
        System.out.println(people);
    }

结果:
在这里插入图片描述

3.bean的作用域

bean的作用域有以下五种:
singleton:单例模式
prototype:原型模式
request,session,application,websoket,这些在Web中使用。

3.1单例模式

单例模式是spring的默认机制,当多次调用bean时,IOC容器指挥创建一个对象。

创建一个bean

 <bean id="hello" class="com.rcy.pojo.Hello" scope="singleton" p:name="lige" p:age="12">
    </bean>

调用两次bean,测试IOC到底创建了几个对象

public  void test2(){
    
    
       ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
       Hello hello = (Hello) context.getBean("hello");
       Hello hello2 = (Hello) context.getBean("hello");
        System.out.println(hello);
        System.out.println(hello2);
        System.out.println(hello==hello2);
    }

结果:
在这里插入图片描述

3.2原型模式

原型模式与单例模式相反,每次调用bean就会创建一个对象
创建一个bean

<bean id="hello" class="com.rcy.pojo.Hello" scope="prototype" p:name="lige" p:age="12">
    </bean>

测试类:

public  void test2(){
    
    
       ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
       Hello hello = (Hello) context.getBean("hello");
       Hello hello2 = (Hello) context.getBean("hello");
        System.out.println(hello);
        System.out.println(hello2);
        System.out.println(hello==hello2);
    }

结果:
在这里插入图片描述

四、Bean的自动装配

动物类:

import org.springframework.beans.factory.annotation.Autowired;

import javax.xml.catalog.Catalog;

public class animals {
    
    

    private String name;
    @Autowired
    private Cat cat;
    @Autowired
    private Dog dog;

    public String getName() {
    
    
        return name;
    }

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

    public Cat getCat() {
    
    
        return cat;
    }

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

    public Dog getDog() {
    
    
        return dog;
    }

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

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

猫类:

public class Cat {
    
    
    public void show(){
    
    
        System.out.println("喵喵喵");
    }
}

狗类:

public class Dog {
    
    
    public void show(){
    
    
        System.out.println("汪汪汪");
    }
}

1.byName自动装配

会自动在容器上下文中查找,和自己对象set方法后面的值对应的bean id

<bean id="cat" class="com.rcy.pojo.Cat"/>
    <bean id="dog" class="com.rcy.pojo.Dog"/>
    <bean id="animals" class="com.rcy.pojo.animals" autowire="byName">
        <property name="name" value="哈哈哈"/>
    </bean>

2.byType自动装配

会自动在容器上下文中查找,和自己对象属性类型相同的bean。

<bean id="cat" class="com.rcy.pojo.Cat"/>
    <bean id="dog" class="com.rcy.pojo.Dog"/>
    <bean id="animals" class="com.rcy.pojo.animals" autowire="byType">
        <property name="name" value="哈哈哈"/>
    </bean>

3.使用注解自动装配

3.1@Autowired

在applicationContext.xml中导入约束和支持。

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/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd">
    <bean id="cat" class="com.rcy.pojo.Cat"/>
    <bean id="dog" class="com.rcy.pojo.Dog"/>
    <bean id="animals" class="com.rcy.pojo.animals"/>

注解自动只能给类中的引用对象装配,一般类型无法自动装配。
@Autowired不仅可以再属性前使用还可以在set方法中使用

public class animals {
    
    

    private String name;
    @Autowired
    private Cat cat;
    private Dog dog;

    public String getName() {
    
    
        return name;
    }

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

    public Cat getCat() {
    
    
        return cat;
    }

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

    public Dog getDog() {
    
    
        return dog;
    }

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

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

3.2@Qualifier

@Autowired下有多个byType重复借助@Qualifier进行byName赋值。

五、使用注解开发

1.@Component注解开发

@Component相当于< bean id =" " class=" "/>

首先导入依赖:

   <dependency>
   	 <groupId>org.springframework</groupId>
   	 <artifactId>spring-webmvc</artifactId>
   	 <version>5.3.10</version>
   </dependency>

导入注解包

	<context:annotation-config/>
    <context:component-scan base-package="com.rcy.pojo"/>

导入约束文件

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

animals类注解开发:

@Component
public class animals {
    
    
    @Value("亚洲")
    private String name;
    @Resource
    @Qualifier
    private Cat cat;
    @Autowired
    private Dog dog;
    @Autowired
    private ID id;
@Component
public class Cat {
    
    
    public void show(){
    
    
        System.out.println("喵喵喵");
    }
}

使用@Component来注入,@Vaule方式赋值。
只有使用@Autowired方法注解注入,当有多个此类对象,才能用@Qualifier

2.@Component衍生的注解理解

@Component有几个衍生理解,在web开发中会使用mvc三层架构。

  • controller(@Controller)
  • service (@Service)
  • doa (@Repository)
    这四个功能都是一致的,都是代表将某个类注册到spring中,装配给bean。

3.@Scope注解

这个注解是用来选择作用域的

@Component
@Scope("prototype")
public class Dog {
    
    
    public void show(){
    
    
        System.out.println("汪汪汪");
    }
}

4.纯java配置spring

用java配置spring最大的改变就是不用.xml核心配置文件了。使用了一个java类来代替beans.xml

首先我们要先建立一个config类:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
@Configuration//代表这是一个配置类,相当于之前我们看到的beans.xml
@ComponentScan("com.rcy.pojo")//扫描这个包
//@Import(Myconfig02.class) 引入外部配置文件

@Configuration//代表这是一个配置类,相当于之前我们看到的beans.xml
@ComponentScan("com.rcy.pojo")//扫描这个包
//@Import(Myconfig02.class) 引入外部配置文件

public class Myconfig01 {
    
    
    @Bean//注册一个bean 就相当于我们之前写的bean标签
         //这个方法的名字相当于之前我们写的bean id
         //这个方法的返回值相当于我们之前bean标签的class属性
    public User user(){
    
    
        return new User(); //返回要注入的bean的对象
    }
    public ID id(){
    
    
        return new ID();
    }
    public father baba(){
    
    
        return new father();
    }

}

我们的实体类:

@Component
public class User {
    
    
    @Value("董瑞龙")
   private String name;
    @Value("123")
    private int id;
    @Autowired
    private father baba;

引用对象:

import org.springframework.stereotype.Component;

@Component
public class father {
    
    
    public void whosmyfather(){
    
    
        System.out.println("任晨阳");
    }
}

测试类:

 public void test06(){
    
    
      ApplicationContext context = new AnnotationConfigApplicationContext(Myconfig01.class);
        User user2 = (User)context.getBean("user");
        System.out.println(user2.getName());
        System.out.println(user2.getid());
        user2.getBaba().whosmyfather();
    }

六、AOP

1.什么是AOP

AOP意为面向切面编程,是通过预编译方式和运行期间动态代理实现程序功能的统一维护的一种技术。AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。

2.使用Spring实现AOP接口

导入一个依赖

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

方式一:使用Spring API接口
加入的日志:

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

服务层接口

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

}

接口实现类:

public class UserServiceImpl implements UserService{
    
    

    public void add() {
    
    
        System.out.println("增加了一个新用户");
    }

    public void select() {
    
    
        System.out.println("查询了一个新用户");
    }

    public void delete() {
    
    
        System.out.println("删除了一个新用户");
    }

    public void update() {
    
    
        System.out.println("修改了一个新用户");
    }
}

applicationCotext.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"
       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
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">
    <bean id="userService" class="com.rcy.service.UserServiceImpl"/>
    <bean id="log" class="com.rcy.log.Log"/>


<!--方式一:使用原生Spring API接口-->
<!--配置AOP:需要导入AOP约束-->
    <aop:config>
<!--    切入点:expression:表达式  execution(要执行的位置)    -->
        <aop:pointcut id="pointcut" expression="execution(* com.rcy.service.UserServiceImpl.*(..))"/>
        <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
    </aop:config>
</beans>

Text测试类:

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

结果:

com.rcy.service.UserServiceImpl的add被执行了
增加了一个新用户

方式二:自定义来实现AOP(主要是切面定义)

自定义切面类:

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

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

配置文件:

	<bean id="diy" class="com.rcy.diy.DitPointCut"/>
   	 <aop:config>
       	 <!--自定义切面,ref要引用的类-->
        	<aop:aspect ref="diy">
            <aop:pointcut id="point" expression="execution(* com.rcy.service.UserServiceImpl.*(..))"/>
            <aop:before method="before" pointcut-ref="point"/>
            <aop:after method="after" pointcut-ref="point"/>
        </aop:aspect>
    </aop:config>

方式三:注解实现AOP

开启注解支持:

<bean id="annnocationPointcut" class="com.rcy.diy.annocationPointcut"/>
<!--    开启注解支持!-->
    <aop:aspectj-autoproxy/>
</beans>

实体类注解实现:

@Aspect//标注这是一个切面
public class annocationPointcut<ProceedingJoinPointding> {
    
    
    @Before("execution(* com.rcy.service.UserServiceImpl.*(..))")
    public void before(){
    
    
        System.out.println("===========执行前========");
    }
    @After("execution(* com.rcy.service.UserServiceImpl.*(..))")
    public void after(){
    
    
        System.out.println("===========执行后========");
    }
    @Around("execution(* com.rcy.service.UserServiceImpl.*(..))")
 public void around(ProceedingJoinPoint jp)throws Throwable{
    
    
     System.out.println("环绕前");
     Object proceed=jp.proceed();
     System.out.println("环绕后");
 }
}

我们可以看到在我们加入环绕之后的横向开发执行顺序:
在这里插入图片描述

七、Spring整合Mybatis

1.导入相关jar包

  • juint
  • mybatis
  • mysql数据库
  • spring相关的
  • aop织入(aspectjweaver)
  • spring-jdbc
  • mybatis-spring【new】
<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.3.10</version>
    </dependency>

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

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>5.3.10</version>
    </dependency>

    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>2.0.2</version>
    </dependency>

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

2.框架图

在这里插入图片描述

3.实现

User实体类:

public class User {
    
    
    private int id;
    private String name;
    public int getId() {
    
    
        return id;
    }

    public void setId(int id) {
    
    
        this.id = id;
    }

    public String getName() {
    
    
        return name;
    }

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

    public User(int id, String name) {
    
    
        this.id = id;
        this.name = name;
    }

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

Mapper接口:

public interface Mapper {
    
    
    public List<User> select();
    public int add(User user);
    public int delete(int id);
}

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.rcy.Dao.Mapper">

<select id="select" resultType="com.rcy.pojo.User">
    select * from teacher;
</select>
    <insert id="add" parameterType="User">
        insert into teacher(id,name) values (#{id},#{name});
    </insert>
    <delete id="delete" parameterType="int">
        delete from teacher where id=#{id};
    </delete>

</mapper>

spring.xml配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">
    <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/test?useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
    </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/rcy/Dao/Mapper.xml"/>
    </bean>


    <!--  sqlsession-->
    <bean id="sqlsession" class="org.mybatis.spring.SqlSessionTemplate">
    <!-- 只能用构造器注入 -->
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>

    <!--配置声明式事务-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
        <!--  结合AOP执行事务的织入-->
        <!--配置事务的通知  -->
        <tx:advice id="txadvice" transaction-manager="transactionManager">
            <tx:attributes>
                <tx:method name="add" propagation="REQUIRED"/>
                <tx:method name="select" propagation="REQUIRED"/>
                <tx:method name="delete" propagation="REQUIRED"/>
            </tx:attributes>
        </tx:advice>

        <!--配置事务切入-->
        <aop:config>
<!--            <aop:pointcut id="txPointcut" expression="execution(* com.rcy.Dao.Mapper.*(..))"/>-->
            <aop:pointcut id="txPointcut" expression="execution(* com.rcy.Dao.Mapper.*(..))"/>
            <aop:advisor advice-ref="txadvice" pointcut-ref="txPointcut"/>
        </aop:config>

</beans>

mybatis-config文档:

<?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.rcy.pojo"/>
</typeAliases>
</configuration>

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"
       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
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">
    <import resource="spring.xml"/>

    <bean id="myspring" class="com.rcy.Dao.UserMappperimpl">
        <property name="sqlSession" ref="sqlsession"/>
    </bean>

    <bean id="myspring2" class="com.rcy.Dao.UserMapperimpl2">
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </bean>
</beans>

UserMapperimpl2接口实现类:

public class UserMapperimpl2 extends SqlSessionDaoSupport implements Mapper{
    
    

    public List<User> select() {
    
    
        User user = new User(9, "老李");
        SqlSession sqlSession = getSqlSession();
        Mapper mapper = sqlSession.getMapper(Mapper.class);
        mapper.add(user);
       // mapper.delete(5);
        return mapper.select();
    }
    
    public int add(User user) {
    
    
        return getSqlSession().getMapper(Mapper.class).add(user);
    }
    
    public int delete(int id) {
    
    
        return getSqlSession().getMapper(Mapper.class).delete(id);
    }
}

Test测试类:

public class Test {
    
    
    @org.junit.Test
    public void select(){
    
    
       ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        Mapper myspring = context.getBean("myspring2", Mapper.class);
        List<User> user = myspring.select();
        for (User user1 : user) {
    
    
            System.out.println(user1);
        }
    }
}

配置事务:

<!--配置声明式事务-->
     <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <property name="dataSource" ref="dataSource"/>
     </bean>
<!--  结合AOP执行事务的织入-->
    <!--配置事务的通知  -->
    <tx:advice id="txadvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="add" propagation="REQUIRED"/>
            <tx:method name="select" propagation="REQUIRED"/>
            <tx:method name="delete" propagation="REQUIRED"/>
            </tx:attributes>
        </tx:advice>

        <!--配置事务切入-->
        <aop:config>
<!--            <aop:pointcut id="txPointcut" expression="execution(* com.rcy.Dao.Mapper.*(..))"/>-->
            <aop:pointcut id="txPointcut" expression="execution(* com.rcy.Dao.Mapper.*(..))"/>
            <aop:advisor advice-ref="txadvice" pointcut-ref="txPointcut"/>
        </aop:config>

猜你喜欢

转载自blog.csdn.net/weixin_50302770/article/details/120951192
今日推荐