spring-AOP【前置通知+后置通知+后置异常通知+环绕通知】最全整合

1、开发环境

jdk8.0+tomcat8.0+IDEA+MySql数据库

2、数据库结构

在这里插入图片描述

3、工程结构

在idea中建立maven工程sm_demo1,并进行如下配置:(idea中jar配置坐标后会自动下载,此处不多做解释)

1、工程配置:

spring-AOP【前置通知+后置通知+后置异常通知+环绕通知】最全整合_第1张图片

2、配置说明

*注意:中spring-bean.xml文件以spring-bean2.xml为主,其他两个请自动忽略
pom.xml:坐标配置
src:该目录下主要存放java代码,其中:
com.lmm.sm.bean:管理java实体类;
com.lmm.sm.dao:持久层代码管理,主要完成对数据库的CRUD;
com.lmm.sm.service:业务层代码管理,主要完成相关的业务处理;;
com.lmm.sm.test:一般用来进行单元测试;
com.lmm.sm.commons:自定义的一个切面类(实际上就是一个代理类);
resources:该目录下主要存放配置文件,其中有:
db.properties:配置数据库的driver、url、username、password

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8
jdbc.username=root
jdbc.password=root

log4j.properties:配置框架日志输出

# Global logging configuration
# developer-->DEBUG productor-->INFO or ERROR
log4j.rootLogger=DEBUG, stdout
# MyBatis logging configuration...
6
log4j.logger.org.mybatis.example.BlogMapper=TRACE
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

mybatis-config.xml:主要进行mybatis框架的配置,我们一般会配置别名、mapper映射等





    
    
        
    
    
    
        
    


spring-bean2.xml:spring框架配置文件,主要用来配置dataSource、sqlSessionFactory等

注意:其中被注解掉的部分也是重点



    
    
    
    
    
    
        
        
        
        
        
        
    
    
    
        
        
        
        
    
    
    
        
        
        
        
    

    
    
    
    
    
    
    
    
        
        
        
        
       
        
        

        
        
    

User.java

/**
 * 用户实体类
 */
public class User implements Serializable {
    private Integer id;
    private String username;
    private String sex;
    private Date birthday;
    private String address;

    public Integer getId() {
        return id;
    }

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

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", sex='" + sex + '\'' +
                ", birthday=" + birthday +
                ", address='" + address + '\'' +
                '}';
    }
}

UserDao

/**
 * dao层接口
 */
public interface UserDao {
    @Select("select *from user")
    @Results(
            id = "userMap",
            value = {
                    @Result(id = true,column = "id",property = "id"),
                    @Result(column = "username",property = "username"),
                    @Result(column = "sex",property = "sex"),
                    @Result(column = "birthday",property = "birthday"),
                    @Result(column = "address",property = "address")


            }
    )
    public List findUsers();
}

UserServiceImpl

/**
 * service层实现类
 */
@Service("userService")//需要在spring-dao.xml中配置扫包等同于
public class UserServiceImpl implements UserService {
    @Autowired//需要在spring-dao.xml中配置相关信息,等同于
    private UserDao userDao;
    public List findUsers() {
        return userDao.findUsers();
    }
}

UserService

/**
 * service层接口
 */
public interface UserService {
    /**
     * 查询所有用户信息
     * @return
     */
    public List findUsers();
}

AspectAround【环绕通知类】

public class AspectAround {
    /**
     * 环绕通知
     * @param joinPoint (加强版连接点)
     */
    public Object time(ProceedingJoinPoint joinPoint){
        Object obj = null;
        long starttime = 0;//开始时间
        long endtime = 0;//结束时间
        try {
            System.out.println("开始事务****************************");
            starttime = System.currentTimeMillis();
            //执行目标方法
            obj = joinPoint.proceed();
            endtime = System.currentTimeMillis();
            System.out.println("提交事务****************************");
        } catch (Throwable throwable) {
            System.out.println("回滚事务****************************");
            throwable.printStackTrace();
        }finally {
            System.out.println("结束事务****************************");
            //计算执行方法的时间
            System.out.println("目标方法执行的时间:======"+(endtime-starttime)+"毫秒");
            //接收目标方法的返回数据
            List users = (List) obj;
            System.out.println("返回数据:++++"+users.toString());
        }
        return obj;
    }
}

AspectCommon【前后置通知类】

public class AspectCommon {
    /**
     * 定义前置通知
     */
    //public void methodBefore(){
    public void methodBefore(JoinPoint joinPoint){
        System.out.println("AspectCommon------------------开始事务!");
        System.out.println("joinPoint.getTarget():"+joinPoint.getTarget());
        System.out.println("joinPoint.getArgs():"+joinPoint.getArgs());
        System.out.println("joinPoint.getSignature():"+joinPoint.getSignature());
    }

    /**
     * 定义后置通知(有返回值)
     * @param returnValue:这个就是目标方法的返回值
     */
    public void methodAfterReturning(Object returnValue){
        System.out.println("AspectCommon------------------提交事务!");
        List users = (List) returnValue;
        System.out.println("AspectCommon------------------:"+users.toString());

    }
    /**
     * 定义后置通知(目标方法异常)
     * @param ex:这个就是目标方法的异常
     */
    public void processException(Exception ex){
        System.out.println("AspectCommon------------------回滚事务!");
        System.out.println("AspectCommon------------------ex:"+ex.getMessage());
        System.out.println("AspectCommon------------------ex:"+ex.getStackTrace());
    }
}

MyAspectAround

public class MyAspectAround implements MethodBeforeAdvice, AfterReturningAdvice {
    /**
     * 后置通知
     * @param o
     * @param method
     * @param objects
     * @param o1
     * @throws Throwable
     */
    public void afterReturning(Object o, Method method, Object[] objects, Object o1) throws Throwable {
        System.out.println("MyAspectAround------------------------后置通知");
    }

    /**
     * 前置通知
     * @param method
     * @param objects
     * @param o
     * @throws Throwable
     */
    public void before(Method method, Object[] objects, Object o) throws Throwable {
        System.out.println("MyAspectAround------------------------前置通知");
    }
}

UserTest【使用jdk的代理实现】

public class UserTest {
   public class UserTest {
    /**
     * 查询所有用户信息
     */
    @Test
    public void findUsers(){
        ApplicationContext context = new ClassPathXmlApplicationContext("spring-bean.xml");
        UserService userService = (UserService) context.getBean("userService");
        List users = userService.findUsers();
        System.out.println(users);
    }
    }

以上测试内容就包含了前置通知+后置通知+后置异常通知+环绕通知,如有疑问,欢迎各位评论

你可能感兴趣的:(spring-AOP【前置通知+后置通知+后置异常通知+环绕通知】最全整合)