首页 > 其他分享 >Spring和Mybatis

Spring和Mybatis

时间:2023-06-06 19:11:15浏览次数:44  
标签:name Spring void id user Mybatis public out

Mybatis和spring

MyBatis

第一个程序

  1. 搭建数据库

    CREATE DATABASE `mybatis`;
    USE `mybatis`;
    DROP TABLE IF EXISTS `user`;
    CREATE TABLE `user` (
      `id` int(20) NOT NULL,
       `name` varchar(30) DEFAULT NULL,
       `pwd` varchar(30) DEFAULT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    insert  into `user`(`id`,`name`,`pwd`) values (1,'狂神','123456'),(2,'张
    三','abcdef'),(3,'李四','987654');
    
  2. 导包

    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.2</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.47</version>
    </dependency>
    
  3. 编写MyBatis核心配置文件

    <?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>
        <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?useSSL=true&amp;useUnicode=true&amp;characterEncoding=utf8"/>
                    <property name="username" value="root"/>
                    <property name="password" value="123456"/>
                </dataSource>
            </environment>
        </environments>
        <mappers>
            <mapper resource="com/kuang/dao/userMapper.xml"/>
            <!--对应的mappe资源r-->
        </mappers>
    </configuration>
    
  4. 编写MyBatis工具类

    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 java.io.IOException;
    import java.io.InputStream;
    public class MybatisUtils {
        //sql工厂
        private static SqlSessionFactory sqlSessionFactory;
        static {
            try {
                //读取配置文件
                String resource = "mybatis-config.xml";
                InputStream inputStream = Resources.getResourceAsStream(resource);
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //获取SqlSession连接
        public static SqlSession getSession(){
            return sqlSessionFactory.openSession();
        }
    }
    
  5. 创建实体类

    public class User {
        private int id;  //id
        private String name;   //姓名
        private String pwd;   //密码
        //构造,有参,无参
        //set/get
        //toString()
    }
    
  6. 编写mapper接口

    import com.kuang.pojo.User;
    import java.util.List;
    public interface UserMapper {
        List<User> selectUser();
    }
    
  7. 编写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.kuang.dao.UserMapper">
      <select id="selectUser" resultType="com.kuang.pojo.User">
        select * from user
      </select>
    </mapper>
    
  8. 测试

    public class MyTest {
        @Test
        public void selectUser() {
            //连接数据库
            SqlSession session = MybatisUtils.getSession();
            //方法一:
            //List<User> users = session.selectList("com.kuang.mapper.UserMapper.selectUser");
            //方法二:
            UserMapper mapper = session.getMapper(UserMapper.class);
            List<User> users = mapper.selectUser();
            for (User user: users){
                System.out.println(user);
            }
            session.close();
        }
    }
    

Maven静态资源过滤问题

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

CRUD

配置文件中namespace中的名称为对应Mapper接口或者Dao接口的完整包名,必须一致!

select

  1. 方式一:直接在方法中传递参数

    1. 在接口方法的参数前加 @Param属性

    2. Sql语句编写的时候,直接取@Param中设置的值即可,不需要单独设置参数类型

      //通过密码和名字查询用户
      User selectUserByNP(@Param("username") String username,@Param("pwd") String 
      pwd);
      /*
          <select id="selectUserByNP" resultType="com.kuang.pojo.User">
            select * from user where name = #{username} and pwd = #{pwd}
          </select>
      */
      
  2. 方式二:使用万能的Map

    1. 在接口方法中,参数直接传递Map;

      User selectUserByNP2(Map<String,Object> map);
      
    2. 编写sql语句的时候,需要传递参数类型,参数类型为map

      <select id="selectUserByNP2" parameterType="map" 
      resultType="com.kuang.pojo.User">
        select * from user where name = #{username} and pwd = #{pwd}
      </select>
      
    3. 在使用方法的时候,Map的 key 为 sql中取的值即可,没有顺序要求!

      Map<String, Object> map = new HashMap<String, Object>();
      map.put("username","小明");
      map.put("pwd","123456");
      User user = mapper.selectUserByNP2(map);
      

insert

  1. 在UserMapper接口中添加对应的方法

    //添加一个用户
    int addUser(User user);
    
  2. 在UserMapper.xml中添加insert语句

    <insert id="addUser" parameterType="com.kuang.pojo.User">
         insert into user (id,name,pwd) values (#{id},#{name},#{pwd})
    </insert>
    

update

  1. 编写接口

    //修改一个用户
    int updateUser(User user);
    
  2. 编写对应的配置文件SQL

<update id="updateUser" parameterType="com.kuang.pojo.User">
    update user set name=#{name},pwd=#{pwd} where id = #{id}
</update>

delete

  1. 编写接口

    //根据id删除用户
    int deleteUser(int id);
    
  2. 编写配置文件

    <delete id="deleteUser" parameterType="int">
        delete from user where id = #{id}
    </delete>
    

小结

  • 所有的增删改操作都需要提交事务!
  • 接口所有的普通参数,尽量都写上@Param参数,尤其是多个参数时,必须写上!
  • 有时候根据业务的需求,可以考虑使用map传递参数!
  • 为了规范操作,在SQL的配置文件中,我们尽量将Parameter参数和resultType都写上!

模糊查询

  1. 第1种:在Java代码中添加sql通配符。
string wildcardname = “%smi%”;
list<name> names = mapper.selectlike(wildcardname);
 
<select id=”selectlike”>
 select * from foo where bar like #{value}
</select>
  1. 第2种:在sql语句中拼接通配符,会引起sql注入

    string wildcardname = “smi”;
    list<name> names = mapper.selectlike(wildcardname);
     
    <select id=”selectlike”>
         select * from foo where bar like "%"#{value}"%"
    </select>
    

配置解析

1. 核心配置文件

  • mybatis-config.xml 系统核心配置文件

  • MyBatis 的配置文件包含了会深深影响 MyBatis 行为的设置和属性信息。

  • 能配置的内容如下:

    configuration(配置)
        properties(属性)
        settings(设置)
        typeAliases(类型别名)
        typeHandlers(类型处理器)
        objectFactory(对象工厂)
        plugins(插件)
        environments(环境配置)
            environment(环境变量)
                transactionManager(事务管理器)
                dataSource(数据源)
        databaseIdProvider(数据库厂商标识)
        mappers(映射器)
    <!-- 注意元素节点的顺序!顺序不对会报错 -->
    

2. environments元素

<environments default="development">
  <environment id="development">
    <transactionManager type="JDBC">
      <property name="..." value="..."/>
    </transactionManager>
    <dataSource type="POOLED">
      <property name="driver" value="${driver}"/>
      <property name="url" value="${url}"/>
      <property name="username" value="${username}"/>
      <property name="password" value="${password}"/>
    </dataSource>
  </environment>
</environments>
  • 配置MyBatis的多套运行环境,将SQL映射到多个不同的数据库上,必须指定其中一个为默认运行环境(通过default指定)

  • 子元素节点:environment

    • 具体的一套环境,通过设置id进行区别,id保证唯一!

    • 子元素节点:transactionManager - [ 事务管理器 ]

      <!-- 语法 -->
      <transactionManager type="[ JDBC | MANAGED ]"/>
      

      详情:点击查看官方文档

  • 子元素节点:数据源(dataSource)

    • dataSource 元素使用标准的 JDBC 数据源接口来配置 JDBC 连接对象的资源。

    • 数据源是必须配置的。

    • 有三种内建的数据源类型

      type="[UNPOOLED|POOLED|JNDI]")
      
      • unpooled: 这个数据源的实现只是每次被请求时打开和关闭连接。
      • pooled: 这种数据源的实现利用“池”的概念将 JDBC 连接对象组织起来 , 这是一种使得
      • 并发 Web 应用快速响应请求的流行处理方式。
      • jndi:这个数据源的实现是为了能在如 Spring 或应用服务器这类容器中使用,容器可以集中或在外部配置数据源,然后放置一个 JNDI 上下文的引用。
      • 数据源也有很多第三方的实现,比如dbcp,c3p0,druid等等....
  1. mappers元素

1. 引入资源方式
<!-- 使用相对于类路径的资源引用 -->
<mappers>
  <mapper resource="org/mybatis/builder/PostMapper.xml"/>
</mappers
<!-- 使用完全限定资源定位符(URL) -->
<mappers>
  <mapper url="file:///var/mappers/AuthorMapper.xml"/>
</mappers>
<!-- 
使用映射器接口实现类的完全限定类名
需要配置文件名称和接口名称一致,并且位于同一目录下
-->
<mappers>
  <mapper class="org.mybatis.builder.AuthorMapper"/>
</mappers>
<!-- 
将包内的映射器接口实现全部注册为映射器
但是需要配置文件名称和接口名称一致,并且位于同一目录下
-->
<mappers>
  <package name="org.mybatis.builder"/>
</mappers>
2. Mapper文件
<?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.kuang.mapper.UserMapper">
    
</mapper>

namespace中文意思:命名空间,作用如下:

  1. namespace和子元素的id联合保证唯一 , 区别不同的mapper

  2. 绑定DAO接口

  • namespace的命名必须跟某个接口同名
  • 接口中的方法与映射文件中sql语句id应该一一对应
  1. namespace命名规则 : 包名+类名

MyBatis 的真正强大在于它的映射语句,这是它的魔力所在。由于它的异常强大,映射器的 XML 文件就显得相对简单。如果拿它跟具有相同功能的 JDBC 代码进行对比,你会立即发现省掉了将近 95% 的代码。MyBatis 为聚焦于 SQL 而构建,以尽可能地为你减少麻烦。

3. Properties优化

官方文档

第一步 ; 在资源目录下新建一个db.properties

#将数据库信息放到这
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?
useSSL=true&useUnicode=true&characterEncoding=utf8
username=root
password=123456

第二步 : 将文件导入properties 配置文件

<configuration>
    <!--导入properties文件-->
    <properties resource="db.properties"/>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="mapper/UserMapper.xml"/>
    </mappers>
</configuration>
4. typeAliases优化

类型别名是为 Java 类型设置一个短的名字。它只和 XML 配置有关,存在的意义仅在于用来减少类完全限定名的冗余。

<!--配置别名,注意顺序-->
<typeAliases>
    <typeAlias type="com.kuang.pojo.User" alias="User"/>
</typeAliases>

当这样配置时,User可以用在任何使用com.kuang.pojo.User的地方。

也可以指定一个包名,MyBatis 会在包名下面搜索需要的 Java Bean,比如:

<typeAliases>
    <package name="com.kuang.pojo"/>
</typeAliases>

每一个在包 com.kuang.pojo 中的 Java Bean,在没有注解的情况下,会使用 Bean 的首字母小写的非限定类名来作为它的别名。

若有注解,则别名为其注解值。见下面的例子

@Alias("user")
public class User {
    ...
}
5. 生命周期和作用域

image-20220210204353748

ResultMap

解决的问题:属性名和字段名不一致

  1. 为列名指定别名 , 别名和java实体类的属性名一致 .

    <select id="selectUserById" resultType="User">
        select id , name , pwd as password from user where id = #{id}
    </select>
    
  2. 使用结果集映射->ResultMap[推荐]

    <!--在对应的mapper.xml文件中-->
    <resultMap id="UserMap" type="User">
        <!-- id为主键 -->
        <id column="id" property="id"/>
        <!-- column是数据库表的列名 , property是对应实体类的属性名 -->
        <result column="name" property="name"/>
        <result column="pwd" property="password"/>
    </resultMap>
    <select id="selectUserById" resultMap="UserMap">
        select id , name , pwd from user where id = #{id}
    </select>
    

自动映射

  • resultMap 元素是 MyBatis 中最重要最强大的元素。它可以让你从 90% 的 JDBC ResultSets 数据提取代码中解放出来。

  • 实际上,在为一些比如连接的复杂语句编写映射代码的时候,一份 resultMap 能够代替实现同等功能的长达数千行的代码。

  • ResultMap 的设计思想是,对于简单的语句根本不需要配置显式的结果映射,而对于复杂一点的语句只需要描述它们的关系就行了。

  • 你已经见过简单映射语句的示例了,但并没有显式指定 resultMap。比如

    <select id="selectUserById" resultType="map">
        select id , name , pwd 
        from user 
        where id = #{id}
    </select>
    

    上述语句只是简单地将所有的列映射到 HashMap 的键上,这由 resultType 属性指定。虽然在大部分情况下都够用,但是 HashMap 不是一个很好的模型。你的程序更可能会使用 JavaBean 或 POJO(Plain Old Java Objects,普通老式 Java 对象)作为模型。

    ResultMap 最优秀的地方在于,虽然你已经对它相当了解了,但是根本就不需要显式地用到他们。

手动映射

  1. 返回值类型为resultMap
<select id="selectUserById" resultMap="UserMap">
    select id , name , pwd from user where id = #{id}
</select>
  1. 编写resultMap,实现手动映射!

    <resultMap id="UserMap" type="User">
        <!-- id为主键 -->
        <id column="id" property="id"/>
        <!-- column是数据库表的列名 , property是对应实体类的属性名 -->
        <result column="name" property="name"/>
        <result column="pwd" property="password"/>
    </resultMap>
    

分页的实现

log4j使用

  1. 导包

    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>
    
  2. 配置文件编写

#将等级为DEBUG的日志信息输出到console和file这两个目的地,console和file的定义在下
面的代码
log4j.rootLogger=DEBUG,console,file
#控制台输出的相关设置
log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.Target = System.out
log4j.appender.console.Threshold=DEBUG
log4j.appender.console.layout = org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=[%c]-%m%n
#文件输出的相关设置
log4j.appender.file = org.apache.log4j.RollingFileAppender
log4j.appender.file.File=./log/kuang.log
log4j.appender.file.MaxFileSize=10mb
log4j.appender.file.Threshold=DEBUG
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%p][%d{yy-MM-dd}][%c]%m%n
#日志输出级别
log4j.logger.org.mybatis=DEBUG
log4j.logger.java.sql=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
  1. setting设置日志实现

    <settings>
        <setting name="logImpl" value="LOG4J"/>
    </settings
    

limit实现分页

#语法
SELECT * FROM table LIMIT stratIndex,pageSize
SELECT * FROM table LIMIT 5,10; // 检索记录行 6-15   
#为了检索从某一个偏移量到记录集的结束所有的记录行,可以指定第二个参数为 -1:    
SELECT * FROM table LIMIT 95,-1; // 检索记录行 96-last.   
#如果只给定一个参数,它表示返回最大的记录行数目:    
SELECT * FROM table LIMIT 5; //检索前 5 个记录行   
#换句话说,LIMIT n 等价于 LIMIT 0,n。

步骤

  1. 修改Mapper文件

    <select id="selectUser" parameterType="map" resultType="user">
        select * from user limit #{startIndex},#{pageSize}
    </select>
    
  2. Mapper接口,参数为map

    //选择全部用户实现分页
    List<User> selectUser(Map<String,Integer> map);
    
  3. 测试

    //分页查询 , 两个参数startIndex , pageSize
    @Test
    public void testSelectUser() {
        SqlSession session = MybatisUtils.getSession();
        UserMapper mapper = session.getMapper(UserMapper.class);
        int currentPage = 1;  //第几页
        int pageSize = 2;  //每页显示几个
        Map<String,Integer> map = new HashMap<String,Integer>();
        map.put("startIndex",(currentPage-1)*pageSize);
        map.put("pageSize",pageSize);
        List<User> users = mapper.selectUser(map);
        for (User user: users){
            System.out.println(user);
        }
        session.close();
    }
    

RowBounds分页

步骤

  1. mapper接口

    //选择全部用户RowBounds实现分页
    List<User> getUserByRowBounds();
    
  2. mapper.xml文件

    <select id="getUserByRowBounds" resultType="user">
      select * from user
    </select>
    
  3. 测试(在这里使用rowBounds)

    @Test
    public void testUserByRowBounds() {
        SqlSession session = MybatisUtils.getSession();
        int currentPage = 2;  //第几页
        int pageSize = 2;  //每页显示几个
        RowBounds rowBounds = new RowBounds((currentPage-1)*pageSize,pageSize);
        //通过session.**方法进行传递rowBounds,[此种方式现在已经不推荐使用了]
        List<User> users = session.selectList("com.kuang.mapper.UserMapper.getUserByRowBounds", null, rowBounds);
        for (User user: users){
            System.out.println(user);
        }
        session.close();
    }
    

注解开发

  • mybatis最初配置信息是基于 XML ,映射语句(SQL)也是定义在 XML 中的。而到MyBatis 3提供了新的基于注解的配置。不幸的是,Java 注解的的表达力和灵活性十分有限。最强大的 MyBatis 映射并不能用注解来构建

  • sql 类型主要分成 :
    @select ()
    @update ()
    @Insert ()
    @delete ()

    步骤

    1. 我们在我们的接口中添加注解
    //查询全部用户
    @Select("select id,name,pwd password from user")
    public List<User> getAllUser();
    
    1. 在mybatis的核心配置文件中注入

      <!--使用class绑定接口-->
      <mappers>
          <mapper class="com.kuang.mapper.UserMapper"/>
      </mappers>
      
    2. 本质上利用了jvm的动态代理机制

      image-20220210211526128

关于@Param

@Param注解用于给方法参数起一个名字。以下是总结的使用原则:

  • 在方法只接受一个参数的情况下,可以不使用@Param。
  • 在方法接受多个参数的情况下,建议一定要使用@Param注解给参数命名。
  • 如果参数是 JavaBean , 则不能使用@Param。
  • 不使用@Param注解时,参数只能有一个,并且是Javabean。

$与#的区别

  • /#{} 的作用主要是替换预编译语句(PrepareStatement)中的占位符? 【推荐使用】

    INSERT INTO user (name) VALUES (#{name});
    INSERT INTO user (name) VALUES (?);
    
  • ${} 的作用是直接进行字符串替换

    INSERT INTO user (name) VALUES ('${name}');
    INSERT INTO user (name) VALUES ('kuangshen');
    

多对一的处理

数据库设计

CREATE TABLE `teacher` (
  `id` INT(10) NOT NULL,
  `name` VARCHAR(30) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8
INSERT INTO teacher(`id`, `name`) VALUES (1, '秦老师'); 
CREATE TABLE `student` (
  `id` INT(10) NOT NULL,
  `name` VARCHAR(30) DEFAULT NULL,
  `tid` INT(10) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `fktid` (`tid`),
  CONSTRAINT `fktid` FOREIGN KEY (`tid`) REFERENCES `teacher` (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('1', '小明', '1'); 
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('2', '小红', '1'); 
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('3', '小张', '1'); 
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('4', '小李', '1'); 
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('5', '小王', '1');

搭建测试环境

[lombok的使用]

  1. IDEA安装lombok

  2. 导入依赖

    <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>1.16.10</version>
    </dependency>
    
  3. 增加注解

    @Data //GET,SET,ToString,有参,无参构造
    public class Teacher {
        private int id;
        private String name;
    }
    
    @Data
    public class Student {
        private int id;
        private String name;
        //多个学生可以是同一个老师,即多对一
        private Teacher teacher;
    }
    
  4. 编写Mapper接口

    public interface StudentMapper {
    }
    
    public interface TeacherMapper {
    }
    
  5. 编写Mapper接口对应的 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.kuang.mapper.StudentMapper">
    </mapper>
    
    <?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.kuang.mapper.TeacherMapper">
    </mapper>
    

按查询嵌套处理

  1. 给StudentMapper接口增加方法

    //获取所有学生及对应老师的信息
    public List<Student> getStudents();
    
  2. 编写对应的Mapper文件

    <?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.kuang.mapper.StudentMapper">
        <!--
        需求:获取所有学生及对应老师的信息
        思路:
            1. 获取所有学生的信息
            2. 根据获取的学生信息的老师ID->获取该老师的信息
            3. 思考问题,这样学生的结果集中应该包含老师,该如何处理呢,数据库中我们一般使用关联查询?
                1. 做一个结果集映射:StudentTeacher
                2. StudentTeacher结果集的类型为 Student
                3. 学生中老师的属性为teacher,对应数据库中为tid。
                   多个 [1,...)学生关联一个老师=> 一对一,一对多
                4. 查看官网找到:association – 一个复杂类型的关联;使用它来处理关联查
    询
        -->
        <select id="getStudents" resultMap="StudentTeacher">
          select * from student
        </select>
        <resultMap id="StudentTeacher" type="Student">
            <!--association关联属性  property属性名 javaType属性类型 column在多的一方的表中的列名-->
            <association property="teacher"  column="tid" javaType="Teacher" select="getTeacher"/>
        </resultMap>
        <!--
        这里传递过来的id,只有一个属性的时候,下面可以写任何值
        association中column多参数配置:
            column="{key=value,key=value}"
            其实就是键值对的形式,key是传给下个sql的取值名称,value是片段一中sql查询的字段名。
        -->
        <select id="getTeacher" resultType="teacher">
            select * from teacher where id = #{id}
        </select>
    </mapper>
    
  3. 测试

    @Test
    public void testGetStudents(){
        SqlSession session = MybatisUtils.getSession();
        StudentMapper mapper = session.getMapper(StudentMapper.class);
        List<Student> students = mapper.getStudents();
        for (Student student : students){
            System.out.println(
                    "学生名:"+ student.getName()
                            +"\t老师:"+student.getTeacher().getName());
        }
    }
    

按结果嵌套查询

  1. 接口方法编写

    public List<Student> getStudents2();
    
  2. 编写对应的mapper文件

    <!--
    按查询结果嵌套处理
    思路:
        1. 直接查询出结果,进行结果集的映射
    -->
    <select id="getStudents2" resultMap="StudentTeacher2" >
        select s.id sid, s.name sname , t.name tname
        from student s,teacher t
        where s.tid = t.id
    </select>
    <resultMap id="StudentTeacher2" type="Student">
        <id property="id" column="sid"/>
        <result property="name" column="sname"/>
        <!--关联对象property 关联对象在Student实体类中的属性-->
        <association property="teacher" javaType="Teacher">
            <result property="name" column="tname"/>
            <!--需要的结果-->
        </association>
    </resultMap>
    
  3. 去mybatis-config文件中注入【此处应该处理过了】

  4. 测试

    @Test
    public void testGetStudents2(){
        SqlSession session = MybatisUtils.getSession();
        StudentMapper mapper = session.getMapper(StudentMapper.class);
        List<Student> students = mapper.getStudents2();
        for (Student student : students){
            System.out.println(
                    "学生名:"+ student.getName()
                            +"\t老师:"+student.getTeacher().getName());
        }
    }
    

小结

  • 按照查询进行嵌套处理就像SQL中的子查询
  • 按照结果进行嵌套处理就像SQL中的联表查询

一对多的处理

实体类编写

@Data
public class Student {
    private int id;
    private String name;
    private int tid;
}

@Data 
public class Teacher {
    private int id;
    private String name;
    //一个老师多个学生
    private List<Student> students;
}

按结果嵌套处理

  1. TeacherMapper接口编写方法

    //获取指定老师,及老师下的所有学生
    public Teacher getTeacher(int id);
    
  2. 编写接口对应的Mapper配置文件

    <mapper namespace="com.kuang.mapper.TeacherMapper">
        <!--
        思路:
            1. 从学生表和老师表中查出学生id,学生姓名,老师姓名
            2. 对查询出来的操作做结果集映射
                1. 集合的话,使用collection!
                    JavaType和ofType都是用来指定对象类型的
                    JavaType是用来指定pojo中属性的类型
                    ofType指定的是映射到list集合属性中pojo的类型。
        -->
        <select id="getTeacher" resultMap="TeacherStudent">
            select s.id sid, s.name sname , t.name tname, t.id tid
            from student s,teacher t
            where s.tid = t.id and t.id=#{id}
        </select>
        <resultMap id="TeacherStudent" type="Teacher">
            <result  property="name" column="tname"/>
            <collection property="students" ofType="Student">
                <result property="id" column="sid" />
                <result property="name" column="sname" />
                <result property="tid" column="tid" />
            </collection>
        </resultMap>
    </mapper>
    
  3. 将Mapper文件注册到MyBatis-config文件中

<mappers>
    <mapper resource="mapper/TeacherMapper.xml"/>
</mappers>
  1. 测试

    @Test
    public void testGetTeacher(){
        SqlSession session = MybatisUtils.getSession();
        TeacherMapper mapper = session.getMapper(TeacherMapper.class);
        Teacher teacher = mapper.getTeacher(1);
        System.out.println(teacher.getName());
        System.out.println(teacher.getStudents());
    }
    

按查询嵌套处理

  1. TeacherMapper接口编写方法

    public Teacher getTeacher2(int id)
    
  2. 编写接口对应的Mapper配置文件

    <select id="getTeacher2" resultMap="TeacherStudent2">
      select * from teacher where id = #{id}
    </select>
    <resultMap id="TeacherStudent2" type="Teacher">
        <!--column是一对多的外键 , 写的是一的主键的列名-->
        <collection property="students" javaType="ArrayList" ofType="Student" column="id" select="getStudentByTeacherId"/>
    </resultMap>
    <select id="getStudentByTeacherId" resultType="Student">
        select * from student where tid = #{id}
    </select>
    
  3. 将Mapper文件注册到MyBatis-config文件中

  4. 测试

    @Test
    public void testGetTeacher2(){
        SqlSession session = MybatisUtils.getSession();
        TeacherMapper mapper = session.getMapper(TeacherMapper.class);
        Teacher teacher = mapper.getTeacher2(1);
        System.out.println(teacher.getName());
        System.out.println(teacher.getStudents());
    }
    

小结

  1. 关联-association
  2. 集合-collection
  3. 所以association是用于一对一和多对一,而collection是用于一对多的关系
  4. JavaType和ofType都是用来指定对象类型的
  • JavaType是用来指定pojo中属性的类型
  • ofType指定的是映射到list集合属性中pojo的类型。

动态sql

1. 环境搭建

新建一个数据库表:blog
字段:id,title,author,create_time,views

CREATE TABLE `blog` (
  `id` varchar(50) NOT NULL COMMENT '博客id',
  `title` varchar(100) NOT NULL COMMENT '博客标题',
  `author` varchar(30) NOT NULL COMMENT '博客作者',
  `create_time` datetime NOT NULL COMMENT '创建时间',
  `views` int(30) NOT NULL COMMENT '浏览量'
) ENGINE=InnoDB DEFAULT CHARSET=utf8
  1. 创建基础工程

  2. IDutil工具类

    public class IDUtil {
        public static String genId(){
            return UUID.randomUUID().toString().replaceAll("-","");
        }
    }
    
  3. 实体类编写

    import java.util.Date;
    public class Blog {
        private String id;
        private String title;
        private String author;
        private Date createTime;
        private int views;
        //set,get....
    }
    
  4. 编写Mapper接口及xml文件

    public interface BolgMapper{
        
    }
    
    <?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.kuang.mapper.BlogMapper">
    </mapper>
    
  5. mybatis核心配置文件,下划线驼峰自动转换(mybatis-config.xml)

    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>
    <!--注册Mapper.xml-->
    <mappers>
      <mapper resource="mapper/BlogMapper.xml"/>
    </mappers>
    
  6. 插入数据

2. if语句

需求:根据作者名字和博客名字来查询博客!如果作者名字为空,那么只根据博客名字查询,反之,则根据作者名来查询

  1. 编写接口类

    //需求1
    List<Blog> queryBlogIf(Map map);
    
  2. 编写sql语句

    <!--需求1:
    根据作者名字和博客名字来查询博客!
    如果作者名字为空,那么只根据博客名字查询,反之,则根据作者名来查询
    select * from blog where title = #{title} and author = #{author}
    -->
    <select id="queryBlogIf" parameterType="map" resultType="blog">
        select * from blog where
        <if test="title != null">
            title = #{title}
        </if>
        <if test="author != null">
            and author = #{author}
        </if>
    </select>
    
  3. 测试

    @Test
    public void testQueryBlogIf(){
        SqlSession session = MybatisUtils.getSession();
        BlogMapper mapper = session.getMapper(BlogMapper.class);
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("title","Mybatis如此简单");
        map.put("author","狂神说");
        List<Blog> blogs = mapper.queryBlogIf(map);
        System.out.println(blogs);
        session.close();
    }
    

    这样写我们可以看到,如果 author 等于 null,那么查询语句为 select * from user where title=#{title},但是如果title为空呢?那么查询语句为 select * from user where and author=#{author},这是错误的 SQL 语句,如何解决呢?请看下面的 where 语句!

3.where语句

修改上面的sql语句

<select id="queryBlogIf" parameterType="map" resultType="blog">
    select * from blog 
    <where>
        <if test="title != null">
            title = #{title}
        </if>
        <if test="author != null">
            and author = #{author}
        </if>
    </where>
</select>

这个“where”标签会知道如果它包含的标签中有返回值的话,它就插入一个‘where’。此外,如果标签返回的内容是以AND 或OR 开头的,则它会剔除掉。【这是我们使用的最多的案例】

4.Set语句

同理,上面的对于查询 SQL 语句包含 where 关键字,如果在进行更新操作的时候,含有 set 关键词,我们怎么处理呢?

  1. 编写接口的方法

    int updateBlog(Map map);
    
  2. sql配置文件

    <!--注意set是用的逗号隔开-->
    <update id="updateBlog" parameterType="map">
        update blog
          <set>
              <if test="title != null">
                  title = #{title},
              </if>
              <if test="author != null">
                  author = #{author}
              </if>
          </set>
        where id = #{id};
    </update>
    
  3. 测试

    @Test
    public void testUpdateBlog(){
        SqlSession session = MybatisUtils.getSession();
        BlogMapper mapper = session.getMapper(BlogMapper.class);
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("title","动态SQL");
        map.put("author","秦疆");
        map.put("id","9d6a763f5e1347cebda43e2a32687a77");
        mapper.updateBlog(map);
        session.close();
    }
    

5.choose语句

有时候,我们不想用到所有的查询条件,只想选择其中的一个,查询条件有一个满足即可,使用 choose 标签可以解决此类问题,类似于 Java 的 switch 语句

  1. 编写接口方法

    List<Blog> queryBlogChoose(Map map);
    
  2. sql配置文件

    <select id="queryBlogChoose" parameterType="map" resultType="blog">
        select * from blog
        <where>
            <choose>
                <when test="title != null">
                     title = #{title}
                </when>
                <when test="author != null">
                    and author = #{author}
                </when>
                <otherwise>
                    and views = #{views}
                </otherwise>
            </choose>
        </where>
    </select>
    
  3. 测试

    @Test
    public void testQueryBlogChoose(){
        SqlSession session = MybatisUtils.getSession();
        BlogMapper mapper = session.getMapper(BlogMapper.class);
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("title","Java如此简单");
        map.put("author","狂神说");
        map.put("views",9999);
        List<Blog> blogs = mapper.queryBlogChoose(map);
        System.out.println(blogs);
        session.close();
    }
    

6.sql片段

有时候可能某个 sql 语句我们用的特别多,为了增加代码的重用性,简化代码,我们需要将这些代码抽取出来,然后使用时直接调用。

提取SQL片段:

<sql id="if-title-author">
    <if test="title != null">
        title = #{title}
    </if>
    <if test="author != null">
        and author = #{author}
    </if>
</sql>

引用sql片段:

<select id="queryBlogIf" parameterType="map" resultType="blog">
    select * from blog
    <where>
        <!-- 引用 sql 片段,如果refid 指定的不在本文件中,那么需要在前面加上 namespace -->
        <include refid="if-title-author"></include>
        <!-- 在这里还可以引用其他的 sql 片段 -->
    </where>
</select>

注意:①、最好基于 单表来定义 sql 片段,提高片段的可重用性
②、在 sql 片段中不要包括 where

7. foreach

将数据库中前三个数据的id修改为1,2,3;
需求:我们需要查询 blog 表中 id 分别为1,2,3的博客信息

  1. 编写接口

    List<Blog> queryBlogForeach(Map map);
    
  2. 编写sql语句

    <select id="queryBlogForeach" parameterType="map" resultType="blog">
        select * from blog
        <where>
            <!--
            collection:指定输入对象中的集合属性
            item:每次遍历生成的对象
            open:开始遍历时的拼接字符串
            close:结束时拼接的字符串
            separator:遍历对象之间需要拼接的字符串
            select * from blog where 1=1 and (id=1 or id=2 or id=3)
          -->
            <!--将ids的元素提出,每个元素为id-->
            <foreach collection="ids"  item="id" open="and (" close=")" 
    separator="or">
                id=#{id}
            </foreach>
        </where>
    </select>
    
  3. 测试

    @Test
    public void testQueryBlogForeach(){
        SqlSession session = MybatisUtils.getSession();
        BlogMapper mapper = session.getMapper(BlogMapper.class);
        HashMap map = new HashMap();
        List<Integer> ids = new ArrayList<Integer>();
        ids.add(1);
        ids.add(2);
        ids.add(3);
        map.put("ids",ids);
        List<Blog> blogs = mapper.queryBlogForeach(map);
        System.out.println(blogs);
        session.close();
    }
    

缓存

1. Mybatis缓存

  • MyBatis包含一个非常强大的查询缓存特性,它可以非常方便地定制和配置缓存。缓存可以极大的提升查询效率。
  • MyBatis系统中默认定义了两级缓存:一级缓存和二级缓存
    • 默认情况下,只有一级缓存开启。(SqlSession级别的缓存,也称为本地缓存)
    • 二级缓存需要手动开启和配置,他是基于namespace级别的缓存。
    • 为了提高扩展性,MyBatis定义了缓存接口Cache。我们可以通过实现Cache接口来自定义二级缓存

2. 一级缓存

  • 一级缓存也叫本地缓存:
    • 与数据库同一次会话期间查询到的数据会放在本地缓存中。
    • 以后如果需要获取相同的数据,直接从缓存中拿,没必须再去查询数据库;
1. 缓存实验
  1. 在mybatis中加入日志,方便测试结果

  2. 编写接口方法

    //根据id查询用户
    User queryUserById(@Param("id") int id);
    
  3. 接口对应的Mapper文件

    <select id="queryUserById" resultType="user">
        select * from user where id = #{id}
    </select>
    
  4. 测试

    @Test
    public void testQueryUserById(){
        SqlSession session = MybatisUtils.getSession();
        UserMapper mapper = session.getMapper(UserMapper.class);
        User user = mapper.queryUserById(1);
        System.out.println(user);
        User user2 = mapper.queryUserById(1);
        System.out.println(user2);
        System.out.println(user==user2);
        session.close();
    }
    
2. 一级缓存失效的四种情况
  • 一级缓存是SqlSession级别的缓存,是一直开启的,我们关闭不了它;
  • 一级缓存失效情况:没有使用到当前的一级缓存,效果就是,还需要再向数据库中发起一次查询请求!
  1. sqlSession不同

    @Test
    public void testQueryUserById(){
        SqlSession session = MybatisUtils.getSession();
        SqlSession session2 = MybatisUtils.getSession();
        UserMapper mapper = session.getMapper(UserMapper.class);
        UserMapper mapper2 = session2.getMapper(UserMapper.class);
        
        User user = mapper.queryUserById(1);
        System.out.println(user);
        User user2 = mapper2.queryUserById(1);
        System.out.println(user2);
        System.out.println(user==user2);
        
        session.close();
        session2.close();
    }
    
  2. sqlSession相同,查询条件不同

  3. sqlSession相同,两次查询之间执行了增删改操作!

  4. sqlSession相同,手动清除一级缓存

    @Test
    public void testQueryUserById(){
        SqlSession session = MybatisUtils.getSession();
        UserMapper mapper = session.getMapper(UserMapper.class);
        User user = mapper.queryUserById(1);
        System.out.println(user);
        session.clearCache();//手动清除缓存
        User user2 = mapper.queryUserById(1);
        System.out.println(user2);
        System.out.println(user==user2);
        session.close();
    }
    

二级缓存

  • 二级缓存也叫全局缓存,一级缓存作用域太低了,所以诞生了二级缓存
  • 基于namespace级别的缓存,一个名称空间,对应一个二级缓存;
  • 工作机制
    • 一个会话查询一条数据,这个数据就会被放在当前会话的一级缓存中;
    • 如果当前会话关闭了,这个会话对应的一级缓存就没了;但是我们想要的是,会话关闭了,一级缓存中的数据被保存到二级缓存中;
    • 新的会话查询信息,就可以从二级缓存中获取内容;
    • 不同的mapper查出的数据会放在自己对应的缓存(map)中;
使用步骤
  1. 开启全局缓存 【mybatis-config.xml】

    <setting name="cacheEnabled" value="true"/>
    
  2. 去每个mapper.xml中配置使用二级缓存,这个配置非常简单;【xxxMapper.xml】

    <cache/>
    官方示例=====>查看官方文档
    <cache
      eviction="FIFO"
      flushInterval="60000"
      size="512"
      readOnly="true"/>
    这个更高级的配置创建了一个 FIFO 缓存,每隔 60 秒刷新,最多可以存储结果对象或列表的 512 个引用,而且返回的对象被认为是只读的,因此对它们进行修改可能会在不同线程中的调用者产生冲突。
    
  3. 代码测试

    • 所有的实体类先实现序列化接口

    • 测试代码

      @Test
      public void testQueryUserById(){
          SqlSession session = MybatisUtils.getSession();
          SqlSession session2 = MybatisUtils.getSession();
          
          UserMapper mapper = session.getMapper(UserMapper.class);
          UserMapper mapper2 = session2.getMapper(UserMapper.class);
          
          User user = mapper.queryUserById(1);
          System.out.println(user);
          session.close();
          
          User user2 = mapper2.queryUserById(1);
          System.out.println(user2);
          System.out.println(user==user2);
          
          session2.close();
      }
      
  4. 原理

image-20220211101900233

EhCache

Ehcache | Reference Documentation

使用

  1. 导入jar包

    <!-- https://mvnrepository.com/artifact/org.mybatis.caches/mybatis-
    ehcache -->
    <dependency>
        <groupId>org.mybatis.caches</groupId>
        <artifactId>mybatis-ehcache</artifactId>
        <version>1.1.0</version>
    </dependency>
    
  2. 在mapper.xml中使用对应的缓存即可

    <mapper namespace = “org.acme.FooMapper” > 
        <cache type = “org.mybatis.caches.ehcache.EhcacheCache” /> 
    </mapper>
    
  3. 编写ehcache.xml文件,如果在加载时未找到/ehcache.xml资源或出现问题,则将使用默认配置

    <?xml version="1.0" encoding="UTF-8"?>
    <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
             updateCheck="false">
        <!--
           diskStore:为缓存路径,ehcache分为内存和磁盘两级,此属性定义磁盘的缓存位
    置。参数解释如下:
           user.home – 用户主目录
           user.dir  – 用户当前工作目录
           java.io.tmpdir – 默认临时文件路径
         -->
        <diskStore path="./tmpdir/Tmp_EhCache"/>
        <defaultCache
                eternal="false"
                maxElementsInMemory="10000"
                overflowToDisk="false"
                diskPersistent="false"
                timeToIdleSeconds="1800"
                timeToLiveSeconds="259200"
                memoryStoreEvictionPolicy="LRU"/>
     
        <cache
                name="cloud_user"
                eternal="false"
                maxElementsInMemory="5000"
                overflowToDisk="false"
                diskPersistent="false"
                timeToIdleSeconds="1800"
                timeToLiveSeconds="1800"
                memoryStoreEvictionPolicy="LRU"/>
        <!--
           defaultCache:默认缓存策略,当ehcache找不到定义的缓存时,则使用这个缓存策
    略。只能定义一个。
         -->
        <!--
          name:缓存名称。
          maxElementsInMemory:缓存最大数目
          maxElementsOnDisk:硬盘最大缓存个数。
          eternal:对象是否永久有效,一但设置了,timeout将不起作用。
          overflowToDisk:是否保存到磁盘,当系统当机时
          timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。仅当
    eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。
          timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建
    时间和失效时间之间。仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存
    活时间无穷大。
          diskPersistent:是否缓存虚拟机重启期数据 Whether the disk store 
    persists between restarts of the Virtual Machine. The default value is 
    false.
          diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默
    认是30MB。每个Cache都应该有自己的一个缓冲区。
          diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。
          memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将
    会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先
    出)或是LFU(较少使用)。
          clearOnFlush:内存数量最大时是否清除。
          memoryStoreEvictionPolicy:可选策略有:LRU(最近最少使用,默认策略)、
    FIFO(先进先出)、LFU(最少访问次数)。
          FIFO,first in first out,这个是大家最熟的,先进先出。
          LFU, Less Frequently Used,就是上面例子中使用的策略,直白一点就是讲一直以
    来最少被使用的。如上面所讲,缓存的元素有一个hit属性,hit值最小的将会被清出缓存。
          LRU,Least Recently Used,最近最少使用的,缓存的元素有一个时间戳,当缓存容
    量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的
    元素将被清出缓存。
       -->
    </ehcache>
    

Spring

IOC本质

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

IoC是Spring框架的核心内容,使用多种方式完美的实现了IoC,可以使用XML配置,也可以使用注解,新版本的Spring也可以零配置实现IoC。

Spring容器在初始化时先读取配置文件,根据配置文件或元数据创建与组织对象存入容器中,程序使用时再从Ioc容器中取出需要的对象。

采用XML方式配置Bean的时候,Bean的定义信息是和实现分离的,而采用注解的方式可以把两者合为一体,Bean的定义信息直接以注解的形式定义在实现类中,从而达到了零配置的目的。

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

第一个Spring

  1. 导包

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.1.10.RELEASE</version>
    </dependency>
    
  2. 编写实体类

    public class Hello {
        private String name;
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public void show(){
            System.out.println("Hello,"+ name );
        }
    }
    
  3. 编写我们的spring文件 , 这里我们命名为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">
        <!--bean就是java对象 , 由Spring创建和管理-->
        <bean id="hello" class="com.kuang.pojo.Hello">
            <property name="name" value="Spring"/>
        </bean>
    </beans>
    
  4. 我们可以去进行测试了 .

    @Test
    public void test(){
        //解析beans.xml文件 , 生成管理相应的Bean对象
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        //getBean : 参数即为spring配置文件中bean的id .
        Hello hello = (Hello) context.getBean("hello");
        hello.show();
    }
    

IOC创建对象方式

1.通过无参构造器创建

  1. User.java

    public class User {
        private String name;
        public User() {
            System.out.println("user无参构造方法");
        }
        public void setName(String name) {
            this.name = name;
        }
        public void show(){
            System.out.println("name="+ name );
        }
    }
    
  2. 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">
        <bean id="user" class="com.kuang.pojo.User">
            <property name="name" value="kuangshen"/>
        </bean>
    </beans>
    
  3. 测试

    @Test
    public void test(){
        ApplicationContext context = new 
    ClassPathXmlApplicationContext("beans.xml");
        //在执行getBean的时候, user已经创建好了 , 通过无参构造
        User user = (User) context.getBean("user");
        //调用对象的方法 .
        user.show();
    }
    

2.通过有参构造方法来创建

  1. UserT . java

    public class UserT {
        private String name;
        public UserT(String name) {
            this.name = name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public void show(){
            System.out.println("name="+ name );
        }
    }
    
  2. beans.xml 有三种方式编写

    <!-- 第一种根据index参数下标设置 -->
    <bean id="userT" class="com.kuang.pojo.UserT">
        <!-- index指构造方法 , 下标从0开始 -->
        <constructor-arg index="0" value="kuangshen2"/>
    </bean>
    
    <!-- 第二种根据参数名字设置 -->
    <bean id="userT" class="com.kuang.pojo.UserT">
        <!-- name指参数名 -->
        <constructor-arg name="name" value="kuangshen2"/>
    </bean>
    
    <!-- 第三种根据参数类型设置 -->
    <bean id="userT" class="com.kuang.pojo.UserT">
        <constructor-arg type="java.lang.String" value="kuangshen2"/>
    </bean>
    
  3. 测试

    @Test
    public void testT(){
        ApplicationContext context = new 
    ClassPathXmlApplicationContext("beans.xml");
        UserT user = (UserT) context.getBean("userT");
        user.show();
    }
    

Spring配置

别名

alias 设置别名 , 为bean设置别名 , 可以设置多个别名

<!--设置别名:在获取Bean的时候可以使用别名获取-->
<alias name="userT" alias="userNew"/>

Bean的配置

<!--bean就是java对象,由Spring创建和管理-->
<!--
    id 是bean的标识符,要唯一,如果没有配置id,name就是默认标识符
    如果配置id,又配置了name,那么name是别名
    name可以设置多个别名,可以用逗号,分号,空格隔开
    如果不配置id和name,可以根据applicationContext.getBean(.class)获取对象;
    class是bean的全限定名=包名+类名
-->
<bean id="hello" name="hello2 h2,h3;h4" class="com.kuang.pojo.Hello">
    <property name="name" value="Spring"/>
</bean>

import

团队的合作通过import来实现 .

<import resource="{path}/beans.xml"/>

依赖注入(DI)

  • 依赖注入(Dependency Injection,DI)。
  • 依赖 : 指Bean对象的创建依赖于容器 . Bean对象的依赖资源 .
  • 注入 : 指Bean对象所依赖的资源 , 由容器来设置和装配

构造器注入

Set注入

要求被注入的属性 , 必须有set方法 , set方法的方法名由set + 属性首字母大写 , 如果属性是boolean类型 , 没有set方法 , 是 is .

测试pojo类 :

Address.java

public class Address {
    private String address;
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
}

Student.java

package com.kuang.pojo;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
public class Student {
    private String name;
    private Address address;
    private String[] books;
    private List<String> hobbys;
    private Map<String,String> card;
    private Set<String> games;
    private String wife;
    private Properties info;
    public void setName(String name) {
        this.name = name;
    }
    public void setAddress(Address address) {
        this.address = address;
    }
    public void setBooks(String[] books) {
        this.books = books;
    }
    public void setHobbys(List<String> hobbys) {
        this.hobbys = hobbys;
    }
    public void setCard(Map<String, String> card) {
        this.card = card;
    }
    public void setGames(Set<String> games) {
        this.games = games;
    }
    public void setWife(String wife) {
        this.wife = wife;
    }
    public void setInfo(Properties info) {
        this.info = info;
    }
    public void show(){
        System.out.println("name="+ name
                + ",address="+ address.getAddress()
                + ",books="
        );
        for (String book:books){
            System.out.print("<<"+book+">>\t");
        }
        System.out.println("\n爱好:"+hobbys);
        System.out.println("card:"+card);
        System.out.println("games:"+games);
        System.out.println("wife:"+wife);
        System.out.println("info:"+info);
    }
}
  1. 常量注入

    <bean id="student" class="com.kuang.pojo.Student">
        <property name="name" value="小明"/>
    </bean>
    

    测试

    @Test
    public void test01(){
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        Student student = (Student) context.getBean("student");
        System.out.println(student.getName());
    }
    
  2. Bean注入

    <bean id="addr" class="com.kuang.pojo.Address">
        <property name="address" value="重庆"/>
    </bean>
    <bean id="student" class="com.kuang.pojo.Student">
        <property name="name" value="小明"/>
        <property name="address" ref="addr"/>
    </bean>
    
  3. 数组注入

    <bean id="student" class="com.kuang.pojo.Student">
        <property name="name" value="小明"/>
        <property name="address" ref="addr"/>
        <property name="books">
            <array>
                <value>西游记</value>
                <value>红楼梦</value>
                <value>水浒传</value>
            </array>
        </property>
    </bean>
    
  4. List注入

    <property name="hobbys">
        <list>
            <value>听歌</value>
            <value>看电影</value>
            <value>爬山</value>
        </list>
    </property>
    
  5. Map注入

    <property name="card">
        <map>
            <entry key="中国邮政" value="456456456465456"/>
            <entry key="建设" value="1456682255511"/>
        </map>
    </property>
    
  6. set注入

    <property name="games">
        <set>
            <value>LOL</value>
            <value>BOB</value>
            <value>COC</value>
        </set>
    </property>
    
  7. Null注入

    <property name="wife"><null/></property>
    
  8. Properties注入

    <property name="info">
        <props>
            <prop key="学号">20190604</prop>
            <prop key="性别">男</prop>
            <prop key="姓名">小明</prop>
        </props>
    </property>
    

拓展注入实现

p命名注入和c命名注入

Bean的作用域

image-20220211192100217

Bean的自动装配

  • 自动装配是使用spring满足bean依赖的一种方法

  • spring会在应用上下文中为某个bean寻找其依赖的bean。

Spring中bean有三种装配机制,分别是:

  1. 在xml中显式配置;

  2. 在java中显式配置;

  3. 隐式的bean发现机制和自动装配。

这里我们主要讲第三种:自动化的装配bean。

Spring的自动装配需要从两个角度来实现,或者说是两个操作:

  1. 组件扫描(component scanning):spring会自动发现应用上下文中所创建的bean;
  2. 自动装配(autowiring):spring自动满足bean之间的依赖,也就是我们说的IoC/DI;

环境搭建

  1. 新建项目

  2. 新建两个实体类,Cat Dog 都有一个叫的方法

    public class Cat {
        public void shout() {
            System.out.println("miao~");
        }
    }
    
    public class Dog {
        public void shout() {
            System.out.println("wang~");
        }
    }
    
  3. 新建一个用户类 User

    public class User {
        private Cat cat;
        private Dog dog;
        private String str;
    }
    
  4. 编写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">
        <bean id="dog" class="com.kuang.pojo.Dog"/>
        <bean id="cat" class="com.kuang.pojo.Cat"/>
        <bean id="user" class="com.kuang.pojo.User">
            <property name="cat" ref="cat"/>
            <property name="dog" ref="dog"/>
            <property name="str" value="qinjiang"/>
        </bean>
    </beans>
    
  5. 测试

    public class MyTest {
        @Test
        public void testMethodAutowire() {
            ApplicationContext context = new 
    ClassPathXmlApplicationContext("beans.xml");
            User user = (User) context.getBean("user");
            user.getCat().shout();
            user.getDog().shout();
        }
    }
    

byName

autowire byName (按名称自动装配)
由于在手动配置xml过程中,常常发生字母缺漏和大小写等错误,而无法对其进行检查,使得开发效率降低。

采用自动装配将避免这些错误,并且使配置简单化。
测试:

  1. 修改bean配置,增加一个属性 autowire="byName"

    <bean id="user" class="com.kuang.pojo.User" autowire="byName">
        <property name="str" value="qinjiang"/>
    </bean>
    
  2. 再次测试,结果依旧成功输出!

  3. 我们将 cat 的bean id修改为 catXXX

  4. 再次测试, 执行时报空指针java.lang.NullPointerException。因为按byName规则找不对应set方
    法,真正的setCat就没执行,对象就没有初始化,所以调用时就会报空指针错误。

小结

当一个bean节点带有 autowire byName的属性时。

  1. 将查找其类中所有的set方法名,例如setCat,或者将set去掉并且首字母小写的字符串,即cat。
  2. 去spring容器中寻找是否有此字符串名称id的对象。
  3. 如果有,就取出注入;如果没有,就报空指针异常。

byType

autowire byType (按类型自动装配)
使用autowire byType首先需要保证:同一类型的对象,在spring容器中唯一。如果不唯一,会报不唯一的异常。

  1. 将user的bean配置修改一下 : autowire="byType"

  2. 测试

  3. 再注册一个cat的bean对象

    <bean id="dog" class="com.kuang.pojo.Dog"/>
    <bean id="cat" class="com.kuang.pojo.Cat"/>
    <bean id="cat2" class="com.kuang.pojo.Cat"/>
    <bean id="user" class="com.kuang.pojo.User" autowire="byType">
        <property name="str" value="qinjiang"/>
    </bean>
    
  4. 测试,报错:NoUniqueBeanDefinitionException

  5. 删掉cat2,将cat的bean名称改掉!测试!因为是按类型装配,所以并不会报异常,也不影响最后的结果。甚至将id属性去掉,也不影响结果。

这就是按照类型自动装配!

使用注解

jdk1.5开始支持注解,spring2.5开始全面支持注解。

准备工作: 利用注解的方式注入属性。

  1. 在spring配置文件中引入context文件头

    xmlns:context="http://www.springframework.org/schema/context"
    http://www.springframework.org/schema/context
    
    http://www.springframework.org/schema/context/spring-context.xsd
    
  2. 开启注解支持(在application-config.xml中修改)

    <context:annotation-config/>
    
  3. @Autowired

    @Autowired是按类型自动转配的,不支持id匹配。

    需要导入 spring-aop的包!

    测试:

    1. 将User类中的set方法去掉,使用@Autowired注解

      public class User {
          @Autowired
          private Cat cat;
          @Autowired
          private Dog dog;
          private String str;
          public Cat getCat() {
              return cat;
          }
          public Dog getDog() {
              return dog;
          }
          public String getStr() {
              return str;
          }
      }
      
    2. 此时配置文件内容

    <context:annotation-config/>
    <bean id="dog" class="com.kuang.pojo.Dog"/>
    <bean id="cat" class="com.kuang.pojo.Cat"/>
    <bean id="user" class="com.kuang.pojo.User"/>
    
  4. @Qualifier

    @Autowired是根据类型自动装配的,加上@Qualifier则可以根据byName的方式自动装配

    @Qualifier不能单独使用。

    测试实验步骤:

    1. 配置文件修改内容,保证类型存在对象。且名字不为类的默认名字!

      <bean id="dog1" class="com.kuang.pojo.Dog"/>
      <bean id="dog2" class="com.kuang.pojo.Dog"/>
      <bean id="cat1" class="com.kuang.pojo.Cat"/>
      <bean id="cat2" class="com.kuang.pojo.Cat"/>
      
    2. 没有加Qualifier测试,直接报错

    3. 在属性上添加Qualifier注解

      @Autowired
      @Qualifier(value = "cat2")
      private Cat cat;
      @Autowired
      @Qualifier(value = "dog2")
      private Dog dog;
      
  5. @Resource

    • @Resource如有指定的name属性,先按该属性进行byName方式查找装配;

    • 其次再进行默认的byName方式进行装配;

    • 如果以上都不成功,则按byType的方式自动装配。

    • 都不成功,则报异常。

      实体类

      public class User {
          //如果允许对象为null,设置required = false,默认为true
          @Resource(name = "cat2")
          private Cat cat;
          @Resource
          private Dog dog;
          private String str;
      }
      

      beans.xml

      <bean id="dog" class="com.kuang.pojo.Dog"/>
      <bean id="cat1" class="com.kuang.pojo.Cat"/>
      <bean id="cat2" class="com.kuang.pojo.Cat"/>
      
      <bean id="user" class="com.kuang.pojo.User"/>
      

      配置文件2:beans.xml , 删掉cat2

      <bean id="dog" class="com.kuang.pojo.Dog"/>
      <bean id="cat1" class="com.kuang.pojo.Cat"/>
      

      实体类上只保留注解

      @Resource
      private Cat cat;
      @Resource
      private Dog dog
      

      结论:先进行byName查找,失败;再进行byType查找,成功。

使用注解开发

说明

在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: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">
</beans>

Bean的实现

我们之前都是使用 bean 的标签进行bean注入,但是实际开发中,我们一般都会使用注解!

  1. 配置扫描哪些包下的注解

    <!--指定注解扫描包-->
    <context:component-scan base-package="com.kuang.pojo"/>
    
  2. 在指定包下编写类,增加注解

@Component("user")
// 相当于配置文件中 <bean id="user" class="当前注解的类"/>
public class User {
    public String name = "秦疆";
}
  1. 测试

    @Test
    public void test(){
        ApplicationContext applicationContext =
            new ClassPathXmlApplicationContext("beans.xml");
        User user = (User) applicationContext.getBean("user");
        System.out.println(user.name);
    }
    

属性注入

使用注解注入属性

  1. 可以不用提供set方法,直接在直接名上添加@value("值")

    @Component("user")
    // 相当于配置文件中 <bean id="user" class="当前注解的类"/>
    public class User {
        @Value("秦疆")
        // 相当于配置文件中 <property name="name" value="秦疆"/>
        public String name;
    }
    
  2. 如果提供了set方法,在set方法上添加@value("值");

    @Component("user")
    public class User {
        public String name;
        @Value("秦疆")
        public void setName(String name) {
            this.name = name;
        }
    }
    

作用域scope

singleton:默认的,Spring会采用单例模式创建这个对象。关闭工厂 ,所有的对象都会销毁。
prototype:多例模式。关闭工厂 ,所有的对象不会销毁。内部的垃圾回收机制会回收

@Controller("user")
@Scope("prototype")
public class User {
    @Value("秦疆")
    public String name;
}

代理模式

  • 静态代理
  • 动态代理

静态代理

静态代理角色分析

  • 抽象角色 : 一般使用接口或者抽象类来实现
  • 真实角色 : 被代理的角色
  • 代理角色 : 代理真实角色 ; 代理真实角色后 , 一般会做一些附属的操作 .
  • 客户 : 使用代理角色来进行一些操作 .

代码实现

Rent . java 即抽象角色

//抽象角色:租房
public interface Rent {
    public void rent();
}

Host . java 即真实角色

//真实角色: 房东,房东要出租房子
public class Host implements Rent{
    public void rent() {
        System.out.println("房屋出租");
}

Proxy . java 即代理角色

//代理角色:中介
public class Proxy implements Rent {
    private Host host;
    public Proxy() { }
    public Proxy(Host host) {
        this.host = host;
    }
    //租房
    public void rent(){
        seeHouse();
        host.rent();
        fare();
    }
    //看房
    public void seeHouse(){
        System.out.println("带房客看房");
    }
    //收中介费
    public void fare(){
        System.out.println("收中介费");
    }
}

Client . java 即客户

//客户类,一般客户都会去找代理!
public class Client {
    public static void main(String[] args) {
        //房东要租房
        Host host = new Host();
        //中介帮助房东
        Proxy proxy = new Proxy(host);
        //你去找中介!
        proxy.rent();
    }
}

分析: 在这个过程中,你直接接触的就是中介,就如同现实生活中的样子,你看不到房东,但是你依旧租到了房东的房子通过代理,这就是所谓的代理模式,程序源自于生活,所以学编程的人,一般能够更加抽象的看待生活中发生的事情。

静态代理的好处

  • 可以使得我们的真实角色更加纯粹 . 不再去关注一些公共的事情 .

  • 公共的业务由代理来完成 . 实现了业务的分工 ,

  • 公共业务发生扩展时变得更加集中和方便 .

缺点 :

  • 类多了 , 多了代理类 , 工作量变大了 . 开发效率降低 .

我们想要静态代理的好处,又不想要静态代理的缺点,所以 , 就有了动态代理 !

动态代理

  • 动态代理的角色和静态代理的一样 .
  • 动态代理的代理类是动态生成的 . 静态代理的代理类是我们提前写好的
  • 动态代理分为两类 : 一类是基于接口动态代理 , 一类是基于类的动态代理
    • 基于接口的动态代理----JDK动态代理
    • 基于类的动态代理--cglib
    • 现在用的比较多的是 javasist 来生成动态代理 . 百度一下javasist
    • 我们这里使用JDK的原生代码来实现,其余的道理都是一样的!

JDK的动态代理需要了解两个类

核心 : InvocationHandler 和 Proxy , 打开JDK帮助文档看看

【InvocationHandler:调用处理程序】

image-20220212094830285

Object invoke(Object proxy, 方法 method, Object[] args);
//参数 
//proxy - 调用该方法的代理实例 
//method -所述方法对应于调用代理实例上的接口方法的实例。 方法对象的声明类将是该方法声明的接
口,它可以是代理类继承该方法的代理接口的超级接口。 
//args -包含的方法调用传递代理实例的参数值的对象的阵列,或null如果接口方法没有参数。 原始
类型的参数包含在适当的原始包装器类的实例中,例如java.lang.Integer或java.lang.Boolean

【Proxy : 代理】

image-20220212094927602

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

代码实现

Rent . java 即抽象角色

//抽象角色:租房
public interface Rent {
    public void rent();
}

Host . java 即真实角色

//真实角色: 房东,房东要出租房子
public class Host implements Rent{
    public void rent() {
        System.out.println("房屋出租");
}

ProxyInvocationHandler. java 即代理角色

public class ProxyInvocationHandler implements InvocationHandler {
    private Rent rent;
    public void setRent(Rent rent) {
        this.rent = rent;
        }
    //生成代理类,重点是第二个参数,获取要代理的抽象角色!之前都是一个角色,现在可以代理一类角色
    public Object getProxy(){
        return Proxy.newProxyInstance(this.getClass().getClassLoader(),
                rent.getClass().getInterfaces(),this);
    }
    // proxy : 代理类 method : 代理类的调用处理程序的方法对象.
    // 处理代理实例上的方法调用并返回结果
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws 
Throwable {
        seeHouse();
        //核心:本质利用反射实现!
        Object result = method.invoke(rent, args);
        fare();
        return result;
    }
    //看房
    public void seeHouse(){
        System.out.println("带房客看房");
    }
    //收中介费
    public void fare(){
        System.out.println("收中介费");
    }
}

Client . java

//租客
public class Client {
    public static void main(String[] args) {
        //真实角色
        Host host = new Host();
        //代理实例的调用处理程序
        ProxyInvocationHandler pih = new ProxyInvocationHandler();
        pih.setRent(host); //将真实角色放置进去!
        Rent proxy = (Rent)pih.getProxy(); //动态生成对应的代理类!
        proxy.rent();
    }
}

核心:一个动态代理 , 一般代理某一类业务 , 一个动态代理可以代理多个类,代理的是接口!

好处

静态代理有的它都有,静态代理没有的,它也有!

  • 可以使得我们的真实角色更加纯粹 . 不再去关注一些公共的事情 .
  • 公共的业务由代理来完成 . 实现了业务的分工 ,
  • 公共业务发生扩展时变得更加集中和方便 .
  • 一个动态代理 , 一般代理某一类业务
  • 一个动态代理可以代理多个类,代理的是接口!

AOP

AOP概念

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

Aop在Spring中的作用

  • 提供声明式事务;允许用户自定义切面横切关注点:跨越应用程序多个模块的方法或功能。即是,与我们业务逻辑无关的,但是我们需要关注的部分,就是横切关注点。如日志 , 安全 , 缓存 , 事务等等 ....
  • 切面(ASPECT):横切关注点 被模块化 的特殊对象。即,它是一个类。
  • 通知(Advice):切面必须要完成的工作。即,它是类中的一个方法。
  • 目标(Target):被通知对象。
  • 代理(Proxy):向目标对象应用通知之后创建的对象。
  • 切入点(PointCut):切面通知 执行的 “地点”的定义。
  • 连接点(JointPoint):与切入点匹配的执行点。

image-20220212100135059

SpringAOP中,通过Advice定义横切逻辑,Spring中支持5种类型的Advice:

image-20220212100207871

实现AOP

  1. 导包

    <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.9.4</version>
    </dependency>
    
第一种方式

编写业务接口和实现类

public interface UserService {
    public void add();
    public void delete();
    public void update();
    public void search();
}
public class UserServiceImpl implements UserService{
    @Override
    public void add() {
        System.out.println("增加用户");
    }
    @Override
    public void delete() {
        System.out.println("删除用户");
    }
    @Override
    public void update() {
        System.out.println("更新用户");
    }
    @Override
    public void search() {
        System.out.println("查询用户");
    }
}

然后去写我们的增强类 , 我们编写两个 , 一个前置增强 一个后置增强

public class Log implements MethodBeforeAdvice {
    //method : 要执行的目标对象的方法
    //objects : 被调用的方法的参数
    //Object : 目标对象
    @Override
    public void before(Method method, Object[] objects, Object o) throws 
Throwable {
        System.out.println( o.getClass().getName() + "的" + method.getName() 
+ "方法被执行了");
    }
}
public class AfterLog implements AfterReturningAdvice {
    //returnValue 返回值
    //method被调用的方法
    //args 被调用的方法的对象的参数
    //target 被调用的目标对象
    @Override
    public void afterReturning(Object returnValue, Method method, Object[] 
args, Object target) throws Throwable {
        System.out.println("执行了" + target.getClass().getName()
        +"的"+method.getName()+"方法,"
        +"返回值:"+returnValue);
    }
}

最后去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"
       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.kuang.service.UserServiceImpl"/>
    <bean id="log" class="com.kuang.log.Log"/>
    <bean id="afterLog" class="com.kuang.log.AfterLog"/>
    <!--aop的配置-->
    <aop:config>
        <!--切入点  expression:表达式匹配要执行的方法-->
        <aop:pointcut id="pointcut" expression="execution(* 
com.kuang.service.UserServiceImpl.*(..))"/>
        <!--执行环绕; advice-ref执行方法 . pointcut-ref切入点-->
        <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
        <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
    </aop:config>
</beans>

测试

public class MyTest {
    @Test
    public void test(){
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        UserService userService = (UserService) context.getBean("userService");
        userService.search();
    }
}
第二种方法

自定义Aop

目标业务类不变依旧是userServiceImpl

第一步 : 写我们自己的一个切入类

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

去spring中配置

<!--第二种方式自定义实现-->
<!--注册bean-->
<bean id="diy" class="com.kuang.config.DiyPointcut"/>
<!--aop的配置-->
<aop:config>
    <!--第二种方式:使用AOP的标签实现-->
    <aop:aspect ref="diy">
        <aop:pointcut id="diyPonitcut" expression="execution(* 
com.kuang.service.UserServiceImpl.*(..))"/>
        <aop:before pointcut-ref="diyPonitcut" method="before"/>
        <aop:after pointcut-ref="diyPonitcut" method="after"/>
    </aop:aspect>
</aop:config>
第三种方式

第一步:编写一个注解实现的增强类

package com.kuang.config;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
@Aspect
public class AnnotationPointcut {
    @Before("execution(* com.kuang.service.UserServiceImpl.*(..))")
    public void before(){
        System.out.println("---------方法执行前---------");
    }
    @After("execution(* com.kuang.service.UserServiceImpl.*(..))")
    public void after(){
        System.out.println("---------方法执行后---------");
    }
    @Around("execution(* com.kuang.service.UserServiceImpl.*(..))")
    public void around(ProceedingJoinPoint jp) throws Throwable {
        System.out.println("环绕前");
        System.out.println("签名:"+jp.getSignature());
        //执行目标方法proceed
        Object proceed = jp.proceed();
        System.out.println("环绕后");
        System.out.println(proceed);
    }
}

第二步:在Spring配置文件中,注册bean,并增加支持注解的配置

<!--第三种方式:注解实现-->
<bean id="annotationPointcut" class="com.kuang.config.AnnotationPointcut"/>
<aop:aspectj-autoproxy/>

aop:aspectj-autoproxy:说明

通过aop命名空间的<aop:aspectj-autoproxy />声明自动为spring容器中那些配置@aspectJ切面的bean创建代理,织入切面。当然,spring 在内部依旧采用AnnotationAwareAspectJAutoProxyCreator进行自动代理的创建工作,但具体实现的细节已经被<aop:aspectj-autoproxy />隐藏起来了 

<aop:aspectj-autoproxy />有一个proxy-target-class属性,默认为false,表示使用jdk动态代理织入增强,当配为<aop:aspectj-autoproxy  poxy-target-class="true"/>时,表示使用CGLib动态代理技术织入增强。不过即使proxy-target-class设置为false,如果目标类没有声明接口,则spring将自动使用CGLib动态代理。

标签:name,Spring,void,id,user,Mybatis,public,out
From: https://www.cnblogs.com/ojky/p/17461469.html

相关文章

  • Spring框架中事务控制的运行原理
    PhotobyTomaszFilipekfromPexels:https://www.pexels.com/photo/nature-photography-of-flower-field-1646178/SpringTransaction基本介绍我们在日常开发中经常使用Spring框架来实现事务管理。事务管理是指在执行一系列操作时,保证这些操作要么全部成功,要么全部失败,不......
  • Mybatisplus分页插件
    两个依赖都需要,否则分页无效<dependency><groupId>com.github.jsqlparser</groupId><artifactId>jsqlparser</artifactId><version>3.1</version></dependency><dependency&......
  • JPA、Hebernate、MyBatis、Spring Data JPA 的区别
    JPA是持久化的标准,是接口协议Hebernate和MyBatis是持久化技术的具体实现SpringDataJPA是在Hibernate的基础上更上层的封装实现1、Hibernate与Jpa的关系?https://www.zhihu.com/question/30691648......
  • idea 创建 spring boot 项目
    1.创建 2.创建信息 next 点finish 3.创建好后,项目长这样: 4.配置maven。如果侧边没有maven选项卡,参考这篇https://www.cnblogs.com/cynthia-wuqian/p/17460845.html   5.启动项目 ......
  • Mybatis 一级缓存与二级缓存
    本文转载于:Mybatis一级缓存与二级缓存的区别你知道吗Mybatis缓存缓存就是内存中的数据,常常来自对数据库查询结果的保存,使用缓存可以避免频繁与数据库进行交互,从而提高查询响应速度。MyBatis提供了对缓存的支持,分为一级缓存和二级缓存,如下图所示:我们先大致了解下MyBatis一......
  • 开始学习spring 最初配置 步骤
    一:新建项目idea-----newproject----在Buildsystem在选择Maven---然后选create创建二:在file中选择ProjectStructure ---- 然后选择Modules----在Depedencies(依赖)中选择 加号 然后在本地电脑上导入所需要的jar包,记得每个jar包之前要选择打上对勾, 然后点击A......
  • spring cloud 项目
    ###项目需求客户端:针对普通用户,用户登录、用户退出、菜品订购、我的订单。后台管理系统:针对管理员,管理员登录、管理员退出、添加菜品、查询菜品、修改菜品、删除菜品、订单处理、添加用户、查询用户、删除用户。![1](/Users/southwind/我的文件/商务合作/ai/项目实战/笔记/images/......
  • 《springboot冲刺棒》application.yml篇
    $是什么意思application.yml中的jdbc:mysql://${MYSQL-HOST:127.0.0.1}的$是什么意思application.yml中的${MYSQL-HOST:127.0.0.1}实际上是SpringBoot应用程序的属性占位符,具有允许在特定位置引用应用程序中定义的属性的功能。在这种情况下,${MYSQL-HOST:127.0.0.1}引用的......
  • MyBatis-plus学习笔记
    1、MyBatis-Plus(简称MP)是一个 MyBatis 的增强工具,在MyBatis的基础上只做增强不做改变,为简化开发、提高效率而生。2、特性:无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑损耗小:启动即会自动注入基本CURD,性能基本无损耗,直接面向对象操作强大的CRUD操作......
  • MybatisPlus代码生成器
    MybatisPlus代码生成器这里讲解的是新版(mybatis-plus3.5.1+版本),旧版不兼容官方文档:https://baomidou.com/(建议多看看官方文档,每种功能里面都有讲解)https://cloud.tencent.com/developer/article/2119707配置这里的配置表格和官方文档一致手动配置代码生成器建表,插入数......