栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Spring(三)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring(三)

Spring

文章目录
  • Spring
    • 十.AOP
      • 1.什么是AOP
      • 2.AOP在Spring中的作用
      • 3.使用Spring实现AOP
    • 十一.整合Mybatis
      • 1.回忆Mybatis
      • 2.Mybatis-Spring
      • 3.sqlSessionDaoSupport
    • 十二.声明式事务
      • 1.回顾事务
      • 2.Spring中的事务管理

十.AOP 1.什么是AOP

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

2.AOP在Spring中的作用

提供声明式事务,允许用户自定义切面

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


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

通知类型连接点实现接口
前置通知方法前org.springframework.aop.MethodBeforeAdvice
后置通知方法后org.springframework.aop.AfterReturningAdvice
环绕通知方法前后org.aopalliance.intercept.MethodInterceptor
异常抛出通知方法抛出异常org.springframeword.aop.ThrowsAdvice
引介通知类中增加新的方法属性org.springframework.aop.IntroductionInterceptor

即Aop在不改变原有代码的情况下,去增加新的功能

3.使用Spring实现AOP

重点:使用AOP织入,需要导入一个依赖包


    org.aspectj
    aspectjweaver
    1.9.9.1

方式一:使用Spring的API接口 (主要是SpringAPI接口实现)
增删改查的接口

package com.mnm.service;

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

实现类:

package com.mnm.service;

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 select() {
        System.out.println("查询了一个用户");
    }
}

日志继承前置通知

package com.mnm.log;

import org.springframework.aop.MethodBeforeAdvice;

import java.lang.reflect.Method;

public class Log implements MethodBeforeAdvice {
    
    @Override
    public void before(Method method, Object[] args, Object target) throws Throwable {
        System.out.println(target.getClass().getName()+"的"+method.getName()+"被执行了");
    }
}

后置通知

package com.mnm.log;

import org.springframework.aop.AfterReturningAdvice;

import java.lang.reflect.Method;

public class AfterLog implements AfterReturningAdvice {
    
    @Override
    public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
        System.out.println("执行了"+method.getName()+"方法返回结果为:"+returnValue);
    }
}

bean配置



    
    
    
    
    
    
    
        
        
        
        
        
    

测试:

import com.mnm.service.UserService;
import com.mnm.service.UserServiceImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        //动态代理的是接口(注意点)
        UserService userService = context.getBean("userService", UserService.class);
        userService.delete();
    }
}
---------------结果---------------
com.mnm.service.UserServiceImpl的delete被执行了
删除了一个用户
执行了delete方法返回结果为:null

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

package com.mnm.diy;

public class DiyPointCut {
    public void before(){
        System.out.println("方法执行前");
    }

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


    
    
    
    
    
        
        
            
            
            
            
            
        
    

import com.mnm.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        //动态代理的是接口(注意点)
        UserService userService = context.getBean("userService", UserService.class);
        userService.delete();
    }
}
---------------结果---------------
方法执行前
删除了一个用户
方法执行后

方式三:使用注解实现

package com.mnm.diy;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;


@Aspect
public class AnnotationPointCut {
    @Before("execution(* com.mnm.service.UserServiceImpl.*(..))")
    public void before(){
        System.out.println("方法执行之前");
    }
    @After("execution(* com.mnm.service.UserServiceImpl.*(..))")
    public void after(){
        System.out.println("方法执行之后");
    }
    
    @Around("execution(* com.mnm.service.UserServiceImpl.*(..))")
    public void around(ProceedingJoinPoint jp) throws Throwable {
        System.out.println("环绕前");
        Signature signature = jp.getSignature();//获得签名
        System.out.println("signature: "+signature);
        //执行方法
        Object proceed = jp.proceed();
        System.out.println("环绕后");
    }
}

applicationContext.xml



    
    
    
    
    
    

测试:

import com.mnm.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        //动态代理的是接口(注意点)
        UserService userService = context.getBean("userService", UserService.class);
        userService.delete();
    }
}
---------------结果---------------
环绕前
signature: void com.mnm.service.UserServiceImpl.delete()
方法执行之前
删除了一个用户
方法执行之后
环绕后
十一.整合Mybatis

步骤:
1.导入相关jar包

  • junit
  • mybatis
  • mysql数据库
  • spring相关的
  • aop织入
  • mybatis-spring[新包]

        
            junit
            junit
            4.12
            test
        
        
            mysql
            mysql-connector-java
            8.0.28
        
        
            org.mybatis
            mybatis
            3.5.9
        
        
            org.springframework
            spring-webmvc
            5.3.19
        
        
        
            org.springframework
            spring-jdbc
            5.3.20
        
        
            org.aspectj
            aspectjweaver
            1.9.9.1
        
        
            org.mybatis
            mybatis-spring
            2.0.7
        
        
            org.projectlombok
            lombok
            1.18.24
        
    

2.编写配置文件
3.测试

1.回忆Mybatis

项目结构:

1.编写实体类

package com.mnm.pojo;

import lombok.Data;

@Data
public class User {
    private int id;
    private String name;
    private String pwd;
}

2.编写核心配置文件
mybatis-config.xml





    
        
    
    
        
            
            
                
                
                
                
            
        
    
    
    
        
    

3.编写工具类

package com.mnm.utils;

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 {
    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();
        }
    }
    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession(true);
    }
}

4.编写接口

package com.mnm.mapper;

import com.mnm.pojo.User;

import java.util.List;

public interface UserMapper {
    public List selectUser();
}

5.编写mapper.xml




    
        select * from user
    

    
        insert into user (id, name, pwd) VALUES (#{id},#{name},#{pwd})
    

    
        delete from user where id=#{id};
    

接口实现类

package com.mnm.mapper;

import com.mnm.pojo.User;
import org.mybatis.spring.support.SqlSessionDaoSupport;

import java.util.List;

public class UserMapperImpl extends SqlSessionDaoSupport implements UserMapper{
    @Override
    public List selectUser() {
        User user = new User(5, "小王", "123123");
        UserMapper mapper = getSqlSession().getMapper(UserMapper.class);
        mapper.addUser(user);
        mapper.deleteUser(5);
        return getSqlSession().getMapper(UserMapper.class).selectUser();
    }

    @Override
    public int addUser(User user) {
        return getSqlSession().getMapper(UserMapper.class).addUser(user);
    }

    @Override
    public int deleteUser(int id) {
        return getSqlSession().getMapper(UserMapper.class).deleteUser(id);
    }
}

在spring配置中,添加事务




    
    
        
        
        
        
    

   
    
        
        
        
        
    
    
    
        
        
    
    
    
        
    

    
    
    
        
        
        
            
            
            
            
            
        
    
    
    
        
        
    

事务的传播特性(propagation)一共有七种:

我们经常使用的就是默认的REQUIRED

测试:

import com.mnm.mapper.UserMapper;
import com.mnm.mapper.UserMapperImpl;
import com.mnm.pojo.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserMapper userMapper = context.getBean("userMapper", UserMapper.class);
        List userList = userMapper.selectUser();
        for (User user : userList) {
            System.out.println(user);
        }
    }
}
---------------结果---------------
User(id=1, name=张三, pwd=123456)
User(id=2, name=孙七, pwd=6666)
User(id=3, name=王五, pwd=123456)
User(id=4, name=赵六, pwd=123456)

为什么需要事务:

  • 如果不配置事务,可能存在数据提交不一致的情况.
  • 如果我们不在spring中声明配置声明式事务,我们就需要在代码中手动配置事务
  • 事务在项目的开发中十分重要,涉及到数据的一致性和完整性,不容马虎
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/924768.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号