Aspectj development of learning achieved Spring AOP

Aspectj is a Java-based framework Aop, Aop It provides powerful features.

Aspectj profile:

  1.Aspectj is an aspect-oriented framework, which extends the Java language, which defines a Aop grammar.

  2. So it has a special compiler to generate the Class file follows the Java language.

  3.Aspectj is a Java-based Aop framework.

  4. After spring2.0, added support for Aspectj entry point expression.

  5. @ Aspectj is newly added after jdk1.5 annotations allow direct section is defined in a class Bean

  6. The new version of spring framework recommended Aspectj way to develop Aop.

  7. Use Aspectj need to import the relevant package: Because Aspectj not part of the spring, and a spring for use with Aop operation, it adds support for Aspectj after spring2.0.

 

Aspectj performed using two methods aop operations:

  1. xml configuration file used to operate Aop

  2. Use annotations to achieve Aop operation.

 

Xml used to implement step profile Aop operation:

  1. Prepare Aop basic package: (1) basic spring packet; (2) the third party dependencies; (3) packet related to Aspectj;

  2. Create a spring core configuration file, import constraints Aop of:

    (1) Configuration of the target class and the bean class section;

    (2) <aop: config> </ aop: config> to create aop

      * <aop:config>  

          <Aop: pointcut expression = "execution ()" id = "" /> // entry point Configuration

          <aop: aspect id = "" ref = " Which section to use bean">       // Configuration section: the process used to enhance the entry points

              <! - Pre-notification ->

              <Aop: before method = "Use enhanced classes (class section) in which (method name)" pointcut-ref = "id which entry point is used" />

              <! - after advice ->

              <aop:after-returning method=""  pointcut-ref=""/>

              <-! Surround Notifications ->

              <aop:around   method=" "   pointcut-ref=" "/>

              <-! Abnormality notification ->

              <aop:after-throwing  method=" " pointcut-ref=" "  throwing="e"/>

              <-! Final notice ->

              <aop:after method=" " pointcut-ref=""/>

           </aop:aspect>

       </aop:config>

 

  In the spring configuration file, configuration section using the <aop: aspect> element, the element will have a defined spring Bean converted to section Bean, so the configuration file should now configure an ordinary spring bean, complete after using <aop: aspect> ref attribute to refer to the element of the bean .

    

 

 

 Based on the xml Aspectj

  1. The introduction of related packages

  

   2. Create an interface UserDao

package com.itheima.jdk;

public interface UserDao {
    public void addUser();
    public void deleteUser();
}

  3. Create a class that implements the interface UserDao

package com.itheima.jdk;

import org.springframework.stereotype.Repository;

public class UserDaoImpl implements UserDao {

    public void addUser() {
        System.out.println("添加用户!");

    }

    public void deleteUser() {
        System.out.println("删除用户!");

    }
}

  4.创建一个切面类

package com.itheima.aspectj.xml;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;

/**
 * 切面类,在此类中编写通知
 * @author 12428
 *
 */
public class MyAspect {
    //前置通知
    public void myBefore(JoinPoint joinPoint) {
        
        System.out.println("前置通知:执行权限检查!");
        
        //joinPoint.getTarget():获取连接点所在的目标对象
        System.out.println("目标类是:"+joinPoint.getTarget());
    
        System.out.println(",被植入曾强的连接点的方法签名:"+joinPoint.getSignature().getName());
    }
    
    //后置通知
    public void myAfterReturning(JoinPoint joinPoint) {
        System.out.println("后置通知:模拟记录日志。。。。");
        System.out.println("被植入曾强通知目标方法为:"+joinPoint.getSignature().getName());
    }
    
    //环绕通知
    /**
     * 环绕通知必须要返回一个Object对象,并且抛出一个错误
     * @param proceedingJoinPoint
     * @return
     * @throws Throwable
     */
    public Object myAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable{
        
        System.out.println("环绕开始:执行目标方法之前:模拟开启事务。。。");
        //执行当前的目标方法:proceed()通过反射执行目标方法连接点处的方法
        Object object=proceedingJoinPoint.proceed();
        System.out.println("环绕结束:执行目标方法之后,模拟关闭事务!");
        
        return object;
        
    }
    
    //异常通知
    public void myAfterThrowing(JoinPoint joinPoint,Throwable e) {
        System.out.println("异常通知:"+"出错了"+e.getMessage());
    }
    
    //最终通知
    public void myAfter() {
        System.out.println("最终通知:模拟方法结束后的释放资源!");
    }
}

 

  5.创建spring配置文件,在com.itheima.aspectj.xml里面

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
        xmlns:aop="http://www.springframework.org/schema/aop"
        xsi:schemaLocation="http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">
        
   
   <!-- 目标类 -->
   <bean id="userDao" class="com.itheima.jdk.UserDaoImpl"/>
   
   <!-- 切面类 -->
   <bean id="myAspect" class="com.itheima.aspectj.xml.MyAspect"/>
   
   <!-- aop编程 -->
   <aop:config>
           <!-- 配置切面 -->
           <aop:aspect ref="myAspect">
               <!-- 3.1配置切入点:并通知最后增强的方法 -->
               <aop:pointcut expression="execution(* com.itheima.jdk.*.*(..))" id="myPointCut"/>
               <!-- 3.2关联通知advice和切入点pointcut -->
                   <!-- 3.2.1前置通知 -->
                   <aop:before method="myBefore" pointcut-ref="myPointCut"/>
                   <!-- 3.2.2后置通知,在方法返回之后执行 -->
                   <aop:after-returning method="myAfterReturning" pointcut-ref="myPointCut"/>
           </aop:aspect>
   </aop:config>
</beans>

  6.测试类,测试

package com.itheima.aspectj.xml;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.itheima.jdk.UserDao;

/**
 * 测试类:用来测试
 * @author 12428
 *
 */
public class TextMyAspect {
    public static void main(String[] args) {
        String xmlPath ="com/itheima/aspectj/xml/applicationContext.xml";
        //得到容器
        ApplicationContext applicationContext=new ClassPathXmlApplicationContext(xmlPath);
        //获取UserDao
        UserDao userDao=(UserDao) applicationContext.getBean("userDao");
        //执行增强后的方法
        userDao.addUser();
    }
}

 

 

 

 

Aspectj使用注解来实现AOP

  使用基于XML的声明式Aspectj开发主要问题是要配置许多的代码信息,为了解决这个问题,Aspectj框架为Aop提供了一套注解,用以取代spring配置文件中为了实现Aop开发所配置的臃肿代码。

aspectj的注解及其描述

 

注解名称 描叙
@Aspect 用于定义一个切面
@PointCut 用于定义切入点表达式,在使用时要定义一个包含名字和任意参数的方法来表示切入点名称,实际上,就是一个返回值为void,且方法体为空的普通方法

@Before

用于定义一个前置通知,在使用时,通常需要制定一个value的属性值,该属性值用于指定一个切入点表达式(可以时已有的切入点表达式,也可以直接定义切入点表达式)
@AfterReturning 用于定义后置通知
@Around 用于定义环绕通知
@AfterThrowing 用于定义异常通知来处理程序中为处理的异常,
@After 用于定义最终通知,不管是否异常,该通知都会执行。

 

 

使用注解来实现AOP操作

  1.引入相关的包

  

   2.创建一个接口UserDao

package com.itheima.jdk;

public interface UserDao {
    public void addUser();
    public void deleteUser();
}

  3.创建一个类实现接口UserDao

package com.itheima.jdk;

import org.springframework.stereotype.Repository;

@Repository("userDao")
public class UserDaoImpl implements UserDao {

    public void addUser() {
        System.out.println("添加用户!");

    }

    public void deleteUser() {
        System.out.println("删除用户!");

    }
}

  4.创建切面类

package com.itheima.aspectj.annotation;

import org.aopalliance.intercept.Joinpoint;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
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;

/**
 * 设置一个切面类,使用注解来执行
 * @author 12428
 *
 */
@Aspect  //声明这是一个切面类
@Component //声明这是一个Bean
public class MyAspect {
    
    //定义一个切入点表达式,并且在下面声明一个方法体为空的
    @Pointcut("execution(* com.itheima.jdk.*.*(..))")
    private void myPointCut() {}
    
    //前置通知
    @Before("myPointCut()")
    public void myBefore(JoinPoint joinPoint) {
        System.out.println("前置通知:模拟执行权限检查..");
        System.out.println("目标类是:"+joinPoint.getTarget());
        System.out.println("被植入的增强处理的目标方法是:"+joinPoint.getSignature().getName());
    }
    
    //后置通知
    @AfterReturning("myPointCut()")
    public void myAfterReturning(JoinPoint joinPoint) {
        System.out.println("后置通知:模拟记录日志。。。。");
        System.out.println("被植入增强的方法是:"+joinPoint.getSignature().getName());
    }
    
    //环绕通知
    @Around("myPointCut()")
    public Object myAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable{
        //开始
        System.out.println("环绕通知开始:执行目标方法之前,模拟开启事务。。。");
        //执行当前目标方法
        Object object=proceedingJoinPoint.getTarget();
        
        //结束
        System.out.println("环绕开始:执行目标方法之后,模拟关闭事务。。。");
        return object;
    }
    
    //异常通知
    @AfterThrowing(value="myPointCut()",throwing="e")
    public void myAfterThrowing(JoinPoint joinPoint,Throwable e) {
        System.out.println("异常通知:"+"出错了"+e.getMessage());
    }
    
    //最终通知
    @After("myPointCut()")
    public void myAfter() {
        System.out.println("最终通知:模拟方法结束后的释放资源!");
    }
    
}

  首先使用了@Aspect注解定义了一个切面类,因为是需要在spring中使用,因此还需要定义一个@Component注解才能生效。然后使用@PointCut注解来定义一个切入点,并通过定义方法来表示一个切入点的名称。

  注意要在目标类UserDaoImpl中添加注解@Respository("UserDao").

  5.创建配置文件,在com.itheima.aspectj.annotation

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  xmlns:aop="http://www.springframework.org/schema/aop"
  xmlns:context="http://www.springframework.org/schema/context"
  xsi:schemaLocation="http://www.springframework.org/schema/beans 
  http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
  http://www.springframework.org/schema/aop 
  http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
  http://www.springframework.org/schema/context 
  http://www.springframework.org/schema/context/spring-context-4.3.xsd">
        
    <!-- 指定需要扫描的包,是注解生效 -->
    <context:component-scan base-package="com.itheima"/>
    <!-- 开启基于注解的声明式Aspectj支持 -->
    <aop:aspectj-autoproxy/>
</beans>

 

  6.测试类

package com.itheima.aspectj.annotation;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.itheima.jdk.UserDao;

//测试类
public class TestAnnotation {
    public static void main(String[] args) {
        String xmlPath="com/itheima/aspectj/annotation/applicationContext.xml";
        ApplicationContext applicationContext=new ClassPathXmlApplicationContext(xmlPath);
        //1.从spring容器获得内容
        UserDao userDao=(UserDao) applicationContext.getBean("userDao");
        userDao.addUser();
    }
}

 

Guess you like

Origin www.cnblogs.com/zhilili/p/11515068.html