Spring-注解开发(Spring+Mybatis)

Posted 永旗狍子

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring-注解开发(Spring+Mybatis)相关的知识,希望对你有一定的参考价值。

目录

Spring-注解开发(Spring+Mybatis)

1.配置pom.xml文件

2.jdbc.properties配置文件

3.application-ann.xml配置文件

4.AOP开发

5.测试

t1() 

t2()


Spring-注解开发(Spring+Mybatis)

1.配置pom.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>Spring-02</artifactId>
    <version>1.0-SNAPSHOT</version>

    <packaging>war</packaging>
    <dependencies>
        <!-- Spring -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.1.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>5.1.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.1.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.1.6.RELEASE</version>
        </dependency>

        <!-- Spring整合mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.1</version>
        </dependency>

        <!-- MyBatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.5</version>
        </dependency>

        <!-- mysql驱动 依赖 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.25</version>
            <scope>runtime</scope>
        </dependency>

        <!-- 连接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.12</version>
        </dependency>

        <!-- Junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>


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

2.jdbc.properties配置文件

#jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/xsh?useUnicode=true&characterEncpding=utf8
jdbc.username=root
jdbc.password=123

3.application-ann.xml配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       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
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       ">
    <!--1.读取jdbc.properties配置文件-->
    <!--classpath:jdbc.properties ==>从class字节码文件的根目录开始-->
    <!--classpath*:jdbc.properties ==>位置不限-->
    <context:property-placeholder location="classpath:jdbc.properties"/>
    <context:component-scan base-package="com.qf"/>
    <!--2.配置数据源-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>
    <!--3.配置sqlsessionFactory-->    <!-- 工厂bean:生成SqlSessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 配置数据源 注入连接池 -->
        <property name="dataSource" ref="dataSource"></property>
        <!-- mapper映射文件,通配符配置方式,可以配置符合条件的所有映射文件 -->
        <property name="mapperLocations" value="classpath*:com/qf/mapper/*.xml"/>
        <!-- 配置实体类别名 -->
        <property name="typeAliasesPackage" value="com.qf.entity"></property>
    </bean>
    <!-- 4.mapperScannerConfigurer -->
    <!-- session.getMapper(接口.class) -->
    <!-- 这个配置会自动帮我们生产接口对应的实现类,实现类的beanName为接口名首字母小写 -->
    <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 配置SqlSessionFactory -->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <!-- 接口包所在位置 -->
        <property name="basePackage" value="com.qf.dao"></property>
    </bean>
    <!-- 5.配置数据库事务管理  -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 配置数据源 -->
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!-- 6.事务注解驱动 -->
    <tx:annotation-driven transaction-manager="transactionManager"/>
    <!-- 7.aop注解驱动 -->
    <aop:aspectj-autoproxy/>
</beans>

4.AOP开发

package com.qf;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.util.Arrays;
/**
 * @author: qiuyongqi
 * @time: 16:49 2021/5/18
 * @description:
 *          @Aspect   此标志为aop增强类
 */
@Component
@Aspect
public class MyAdvice {

    /**
     * @author: qiuyongqi
     * @time: 16:50 2021/5/18
     * @description:   使用空方法设置切点表达式,后面其他增强可以使用方法名来找到我们设置的切点表达式
     */
    @Pointcut("execution(* com.qf.Services..*.*(..))")
    public void pointCut(){}


    /**
     * @author: qiuyongqi
     * @time: 17:05 2021/5/18
     * @description:  前置增强,应用pointCut()方法设置的切点表达式
     */
    @Before("pointCut()")
    public void before(JoinPoint jp){
        System.out.println("前置增强");
        System.out.println("方法名:"+jp.getSignature().getName());
        System.out.println("方法参数列表:"+ Arrays.toString(jp.getArgs()));
    }

    /**
     * @author: qiuyongqi
     * @time: 17:11 2021/5/18
     * @description: 后置增强 returning="ret" 代表后置增强的方法返回值是ret
     */
    @AfterReturning(value = "pointCut()",returning = "ret")
    public void after(JoinPoint jp,Object ret){
        System.out.println("后置增强");
        System.out.println("方法名:"+jp.getSignature().getName());
        System.out.println("方法采纳数列表:"+Arrays.toString(jp.getArgs()));
        System.out.println("返回值:"+ret);
    }

    /**
     * @author: qiuyongqi
     * @time: 17:14 2021/5/18
     * @description: 环绕增强
     */
    @Around("pointCut()")
    public Object interceptor(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("环绕前置----------------------");
        System.out.println();
        Object proceed=pjp.proceed();
        System.out.println();
        System.out.println("环绕后置----------------------");
        return proceed;
    }

    @AfterThrowing(value = "pointCut()",throwing = "ex")
    public void ThrowExec(JoinPoint jp,Exception ex){
        System.out.println("异常增强");
        System.out.println("方法名:"+jp.getSignature().getName());
        System.out.println("方法参数列表:"+ Arrays.toString(jp.getArgs()));
        System.out.println("异常信息是"+ex.getMessage());


    }


}

5.测试

import com.qf.Services.EmpService;
import com.qf.entity.Emp;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.sql.Date;
import java.util.List;

/**
 * @author: qiuyongqi
 * @time: 17:30 2021/5/18
 * @description:
 */

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:application-ann.xml")
public class text2 {
    @Autowired
    private EmpService empService;

    @Test
    public void t1(){
        List<Emp> list = empService.selectAll();
        for (Emp emp : list) {
            System.out.println(emp);
        }

    }

    @Test
    public void t2(){
        Emp emp1 = new Emp("张三12", "男", 20000, "132456", 102, new Date(1));
        System.out.println(empService.addEmp(emp1));
    }
    @Test
    public void t3(){
         System.out.println(empService.delEmp(1078));
    }

    @Test
    public void t4(){
        Emp emp1 = new Emp(1079,"张三12", "男", 20000, "132456", 102, new Date(1));

        System.out.println(empService.updateEmp(emp1));
    }
}

t1() 

t2()

 

以上是关于Spring-注解开发(Spring+Mybatis)的主要内容,如果未能解决你的问题,请参考以下文章

spring+mybati java config配置引起的bean相互引用日志报警告问题

Spring 注解开发和测试

Spring纯注解开发模式简直就是Spring中的Spring

Spring 注解开发 -- Spring新注解(完全替换Spring配置文件 使用配置类)

Spring Boot系列SpringBoot配置全局事务处理

Spring框架--Spring注解开发