2020-10-26

  • 1. Java中的注解

  • 2. 使用 元注解 来自定义注解 和 处理自定义注解

  • 3. spring的bean容器相关的注解

  • 4. spring中注解的处理

  • 5. Spring注解和JSR-330标准注解的区别:


Spring中的注解大概可以分为两大类:

  1. spring的bean容器相关的注解,或者说bean工厂相关的注解;

  2. springmvc相关的注解。

spring的bean容器相关的注解,先后有:@Required, @Autowired, @PostConstruct, @PreDestory,还有Spring3.0开始支持的JSR-330标准javax.inject.*中的注解(@Inject, @Named, @Qualifier, @Provider, @Scope, @Singleton).

springmvc相关的注解有:@Controller, @RequestMapping, @RequestParam, @ResponseBody等等。

要理解Spring中的注解,先要理解Java中的注解。

1. Java中的注解

Java中1.5中开始引入注解,我们最熟悉的应该是:@Override, 它的定义如下:

/**
 * Indicates that a method declaration is intended to override a
 * method declaration in a supertype. If a method is annotated with
 * this annotation type compilers are required to generate an error
 * message unless at least one of the following conditions hold:
 * The method does override or implement a method declared in a
 * supertype.
 * The method has a signature that is override-equivalent to that of
 * any public method declared in Object.
 *
 * @author  Peter von der Ahé
 * @author  Joshua Bloch
 * @jls 9.6.1.4 @Override
 * @since 1.5
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Override {
}

从注释,我们可以看出,@Override的作用是,提示编译器,使用了@Override注解的方法必须override父类或者java.lang.Object中的一个同名方法。我们看到@Override的定义中使用到了 @Target, @Retention,它们就是所谓的“元注解”——就是定义注解的注解,或者说注解注解的注解(晕了...)。我们看下@Retention

/**
 * Indicates how long annotations with the annotated type are to
 * be retained.  If no Retention annotation is present on
 * an annotation type declaration, the retention policy defaults to
 * RetentionPolicy.CLASS.
 */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Retention {
    /**
     * Returns the retention policy.
     * @return the retention policy
     */
    RetentionPolicy value();
}

@Retention用于提示注解被保留多长时间,有三种取值:

public enum RetentionPolicy {
    /**
     * Annotations are to be discarded by the compiler.
     */
    SOURCE,
    /**
     * Annotations are to be recorded in the class file by the compiler
     * but need not be retained by the VM at run time.  This is the default
     * behavior.
     */
    CLASS,
    /**
     * Annotations are to be recorded in the class file by the compiler and
     * retained by the VM at run time, so they may be read reflectively.
     *
     * @see java.lang.reflect.AnnotatedElement
     */
    RUNTIME
}

RetentionPolicy.SOURCE 保留在源码级别,被编译器抛弃(@Override就是此类);RetentionPolicy.CLASS被编译器保留在编译后的类文件级别,但是被虚拟机丢弃;

RetentionPolicy.RUNTIME保留至运行时,可以被反射读取。

再看 @Target:

package java.lang.annotation;

/**
 * Indicates the contexts in which an annotation type is applicable. The
 * declaration contexts and type contexts in which an annotation type may be
 * applicable are specified in JLS 9.6.4.1, and denoted in source code by enum
 * constants of java.lang.annotation.ElementType
 * @since 1.5
 * @jls 9.6.4.1 @Target
 * @jls 9.7.4 Where Annotations May Appear
 */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Target {
    /**
     * Returns an array of the kinds of elements an annotation type
     * can be applied to.
     * @return an array of the kinds of elements an annotation type
     * can be applied to
     */
    ElementType[] value();
}

@Target用于提示该注解使用的地方,取值有:

public enum ElementType {
    /** Class, interface (including annotation type), or enum declaration */
    TYPE,
    /** Field declaration (includes enum constants) */
    FIELD,
    /** Method declaration */
    METHOD,
    /** Formal parameter declaration */
    PARAMETER,
    /** Constructor declaration */
    CONSTRUCTOR,
    /** Local variable declaration */
    LOCAL_VARIABLE,
    /** Annotation type declaration */
    ANNOTATION_TYPE,
    /** Package declaration */
    PACKAGE,
    /**
     * Type parameter declaration
     * @since 1.8
     */
    TYPE_PARAMETER,
    /**
     * Use of a type
     * @since 1.8
     */
    TYPE_USE
}

分别表示该注解可以被使用的地方:

  1. 类,接口,注解,enum;

  2. 属性域;

  3. 方法;

  4. 参数;

  5. 构造函数;

  6. 局部变量;

  7. 注解类型;

所以:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Override {
}

表示 @Override 只能使用在方法上,保留在源码级别,被编译器处理,然后抛弃掉。

还有一个经常使用的元注解 @Documented :

/**
 * Indicates that annotations with a type are to be documented by javadoc
 * and similar tools by default.  This type should be used to annotate the
 * declarations of types whose annotations affect the use of annotated
 * elements by their clients.  If a type declaration is annotated with
 * Documented, its annotations become part of the public API
 * of the annotated elements.
 */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Documented {
}

表示注解是否能被 javadoc 处理并保留在文档中。

2. 使用 元注解 来自定义注解 和 处理自定义注解

有了元注解,那么我就可以使用它来自定义我们需要的注解。结合自定义注解和AOP或者过滤器,是一种十分强大的武器。比如可以使用注解来实现权限的细粒度的控制——在类或者方法上使用权限注解,然后在AOP或者过滤器中进行拦截处理。下面是一个关于登录的权限的注解的实现:

/**
 * 不需要登录注解
 */
@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface NoLogin {
}

我们自定义了一个注解 @NoLogin, 可以被用于 方法 和 类 上,注解一直保留到运行期,可以被反射读取到。该注解的含义是:被 @NoLogin 注解的类或者方法,即使用户没有登录,也是可以访问的。下面就是对注解进行处理了:

/**
 * 检查登录拦截器
 * 如不需要检查登录可在方法或者controller上加上@NoLogin
 */
public class CheckLoginInterceptor implements HandlerInterceptor {
    private static final Logger logger = Logger.getLogger(CheckLoginInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            logger.warn("当前操作handler不为HandlerMethod=" + handler.getClass().getName() + ",req="
                        + request.getQueryString());
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        String methodName = handlerMethod.getMethod().getName();
        // 判断是否需要检查登录
        NoLogin noLogin = handlerMethod.getMethod().getAnnotation(NoLogin.class);
        if (null != noLogin) {
            if (logger.isDebugEnabled()) {
                logger.debug("当前操作methodName=" + methodName + "不需要检查登录情况");
            }
            return true;
        }
        noLogin = handlerMethod.getMethod().getDeclaringClass().getAnnotation(NoLogin.class);
        if (null != noLogin) {
            if (logger.isDebugEnabled()) {
                logger.debug("当前操作methodName=" + methodName + "不需要检查登录情况");
            }
            return true;
        }
        if (null == request.getSession().getAttribute(CommonConstants.SESSION_KEY_USER)) {
            logger.warn("当前操作" + methodName + "用户未登录,ip=" + request.getRemoteAddr());
            response.getWriter().write(JsonConvertor.convertFailResult(ErrorCodeEnum.NOT_LOGIN).toString()); // 返回错误信息
            return false;
        }
        return true;
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response,
                           Object handler, ModelAndView modelAndView) throws Exception {
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                Object handler, Exception ex) throws Exception {
    }
}

上面我们定义了一个登录拦截器,首先使用反射来判断方法上是否被 @NoLogin 注解:

NoLoginnoLogin=handlerMethod.getMethod().getAnnotation(NoLogin.class);

然后判断类是否被 @NoLogin 注解:

noLogin=handlerMethod.getMethod().getDeclaringClass().getAnnotation(NoLogin.class);

如果被注解了,就返回 true,如果没有被注解,就判断是否已经登录,没有登录则返回错误信息给前台和false. 这是一个简单的使用 注解 和 过滤器 来进行权限处理的例子。扩展开来,那么我们就可以使用注解,来表示某方法或者类,只能被具有某种角色,或者具有某种权限的用户所访问,然后在过滤器中进行判断处理。

3. spring的bean容器相关的注解

1)@Autowired 是我们使用得最多的注解,其实就是 autowire=byType 就是根据类型的自动注入依赖(基于注解的依赖注入),可以被使用再属性域,方法,构造函数上。

2)@Qualifier 就是 autowire=byName, @Autowired注解判断多个bean类型相同时,就需要使用 @Qualifier("xxBean") 来指定依赖的bean的id:

@Controller
@RequestMapping("/user")
public class HelloController {
    @Autowired
    @Qualifier("userService")
    private UserService userService;

3)@Resource 属于JSR250标准,用于属性域额和方法上。也是 byName 类型的依赖注入。使用方式:@Resource(name="xxBean"). 不带参数的 @Resource 默认值类名首字母小写。

4)JSR-330标准javax.inject.*中的注解(@Inject, @Named, @Qualifier, @Provider, @Scope, @Singleton)。@Inject就相当于@Autowired, @Named 就相当于 @Qualifier, 另外 @Named 用在类上还有 @Component的功能。

5)@Component, @Controller, @Service, @Repository, 这几个注解不同于上面的注解,上面的注解都是将被依赖的bean注入进入,而这几个注解的作用都是生产bean, 这些注解都是注解在类上,将类注解成spring的bean工厂中一个一个的bean。@Controller, @Service, @Repository基本就是语义更加细化的@Component。

6)@PostConstruct 和 @PreDestroy 不是用于依赖注入,而是bean 的生命周期。类似于 init-method(InitializeingBean) destory-method(DisposableBean)

4. spring中注解的处理

spring中注解的处理基本都是通过实现接口 BeanPostProcessor 来进行的:

public interface BeanPostProcessor {
    Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException;
    Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException;
}

相关的处理类有:AutowiredAnnotationBeanPostProcessor,CommonAnnotationBeanPostProcessor,PersistenceAnnotationBeanPostProcessor,RequiredAnnotationBeanPostProcessor

这些处理类,可以通过 context:annotation-config/ 配置隐式的配置进spring容器。这些都是依赖注入的处理,还有生产bean的注解(@Component, @Controller, @Service, @Repository)的处理:

<context:component-scan base-package="net.aazj.service,net.aazj.aop" />

这些都是通过指定扫描的基包路径来进行的,将他们扫描进spring的bean容器。注意context:component-scan也会默认将 AutowiredAnnotationBeanPostProcessor,CommonAnnotationBeanPostProcessor 配置进来。所以context:annotation-config/是可以省略的。另外context:component-scan也可以扫描@Aspect风格的AOP注解,但是需要在配置文件中加入 aop:aspectj-autoproxy/ 进行配合。

 

 

 

Spring注解之@Component详细解析

1、@controller 控制器(注入服务)

2、@service 服务(注入dao)

3、@repository dao(实现dao访问)

4、@component (把普通pojo实例化到spring容器中,相当于配置文件中的<bean id="" class=""/>)

   @Component,@Service,@Controller,@Repository注解的类,并把这些类纳入进spring容器中管理

下面写这个是引入component的扫描组件 

<context:component-scan base-package=”com.mmnc”> (这是最早的时候读取包所用)

1、@Service用于标注业务层组件 
2、@Controller用于标注控制层组件(如struts中的action) 
3、@Repository用于标注数据访问组件,即DAO组件. 
4、@Component泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注

@Component是一个元注解,意思是可以注解其他类注解,如@Controller @Service @Repository @Aspect。官方的原话是:带此注解的类看为组件,当使用基于注解的配置和类路径扫描的时候,这些类就会被实例化。其他类级别的注解也可以被认定为是一种特殊类型的组件,比如@Repository @Aspect。所以,@Component可以注解其他类注解。

源代码:

@Target({java.lang.annotation.ElementType.TYPE})
           @Retention(RetentionPolicy.RUNTIME)
           @Documented
           public @interface Component {

        //这个值可能作为逻辑组件(即类)的名称,在自动扫描的时候转化为spring bean,即相当<bean id="" class="" />中的id
                   public abstract String value();
            }

 

案例:

a.不指定bean的名称,默认为类名首字母小写university

@Component

public class University {

          to do sthing...

}

获取bean方式:

ApplicationContext ctx  = new ClassPathXmlApplicationContext("./config/applicationContext.xml");
           University ust = (University) ctx.getBean("university");

b.指定bean的名称

@Component("university1")

public class University {

          to do sthing...

}

获取bean方式:

ApplicationContext ctx  = new ClassPathXmlApplicationContext("./config/applicationContext.xml");
           University ust = (University) ctx.getBean("university1");

 

 

 

 

 

本例子是列举基于@Aspect注解

编写切面是开发中一个很重要的环节,能让我们的业务代码更加注重本身代码的实现。可以把其他业务线也用到的一些相同的点提取成切面,方便管理。

例子:

如果将一个大剧场看成一个系统,里面很多演出厅则是系统中的一条条不同的业务线,演出厅的主要业务代码是实现自身的演出。但是每个演出厅都会有观众,观众的进场,喝彩,以及演出失败的退票,大剧场系统也必须要要处理。这个时候就可以把观众看成一个切面。统一在切面管理观众的行为。如:入场前关闭手机、就座、喝彩、演出不尽人意时要求退款。

首先剧场有一个通用的演出接口

 

package com.zhy.edu.aop;

/**
 * 
 * <p>Title:</p>
 * <p>Description:演出通用接口</p>
 * @author zhyHome 
 * @date 2019年8月11日  
 * @version 1.0
 */
public interface Performance {

    /**
     * 
     * <p>@Title: perform</p>   
     * <p>@Description: 演出</p>  
     * @author zhyHome 
     * @date 2019年8月11日   
     * @param:       
     * @return: void      
     * @throws   
     * @version 1.0
     */
    public void perform() throws Exception;
}

观众类,然后观众会基于演出做出一系列的行为

 

package com.zhy.edu.aop;

import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.annotation.Configuration;

/**
 * 
 * <p>Title:</p>
 * <p>Description:观众切面</p>
 * @author zhyHome 
 * @date 2019年8月11日  
 * @version 1.0
 */
@Aspect
@Configuration
public class Audience {
    
    /**
     * 
     * <p>@Title: performance</p>   
     * <p>@Description: 通用切点</p>  
     * @author zhyHome 
     * @date 2019年8月11日   
     * @param:       
     * @return: void      
     * @throws   
     * @version 1.0
     */
    @Pointcut("execution(** com.zhy.edu.aop.Performance.perform(..))")
    public void performance() {};

    /**
     * 
     * <p>@Title: beforeMethod</p>   
     * <p>@Description: 关闭手机(调用通用切点时只需要写通用切点的方法名)</p>  
     * @author zhyHome 
     * @date 2019年8月11日   
     * @param:       
     * @return: void      
     * @throws   
     * @version 1.0
     */
    @Before("performance()")
    public void silenceCellPhone() {
        System.out.println("观众表演之前关闭手机");
    }
    
    /**
     * 
     * <p>@Title: takeSeats</p>   
     * <p>@Description: 观众就坐</p>  
     * @author zhyHome 
     * @date 2019年8月11日   
     * @param:       
     * @return: void      
     * @throws   
     * @version 1.0
     */
    @Before("performance()")
    public void takeSeats() {
        System.out.println("观众就坐");
    }
    
    /**
     * 
     * <p>@Title: applause</p>   
     * <p>@Description: 观众喝彩</p>  
     * @author zhyHome 
     * @date 2019年8月11日   
     * @param:       
     * @return: void      
     * @throws   
     * @version 1.0
     */
    @AfterReturning("performance()")
    public void applause() {
        System.out.println("观众喝彩");
    }
    
    /**
     * 
     * <p>@Title: demandRefund</p>   
     * <p>@Description: 观众退款</p>  
     * @author zhyHome 
     * @date 2019年8月11日   
     * @param:       
     * @return: void      
     * @throws   
     * @version 1.0
     */
    @AfterThrowing("performance()")
    public void demandRefund() {
        System.out.println("观众退款");
    }
}

不同的演出厅的演出类

雨燕演出厅

 

package com.zhy.edu.aop;

import org.springframework.stereotype.Component;

@Component
public class SwiftDrama implements Performance{

    @Override
    public void perform() throws Exception {
        int random = ((int)(10 * Math.random()))%2;
        System.out.println("雨燕话剧演出中");
        if (random == 1) {
            System.out.println("完美演出");
        }else {
            System.err.println("演出失败");
            throw new Exception();
        }
    }

    
}

泰坦尼克演出厅

 

package com.zhy.edu.aop;

import org.springframework.stereotype.Component;

/**
 * 
 * <p>Title:</p>
 * <p>Description:泰坦尼克话剧</p>
 * @author zhyHome 
 * @date 2019年8月11日  
 * @version 1.0
 */
@Component
public class TitanicDrama implements Performance{

    @Override
    public void perform() throws Exception {
        int random = ((int)(10 * Math.random()))%2;
        System.out.println("泰坦尼克话剧演出中");
        if (random == 1) {
            System.out.println("完美演出");
        }else {
            System.err.println("演出失败");
            throw new Exception();
        }
    }

}

执行演出业务代码(junit测试类)

 

package com.zhy.edu;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import com.zhy.edu.aop.SwiftDrama;
import com.zhy.edu.aop.TitanicDrama;

@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationTests {

    @Autowired
    TitanicDrama performance;
    
    @Autowired
    SwiftDrama swiftDrama;

    /**
     * 
     * <p>@Title: performance</p>   
     * <p>@Description: 演出厅测试</p>  
     * @author zhyHome 
     * @date 2019年8月11日   
     * @param:       
     * @return: void      
     * @throws   
     * @version 1.0
     */
    @Test
    public void performance() {
        try {
            System.out.println("---------------------演出厅1:--------------------");
            performance.perform();
            
        } catch (Exception e) {
        }
        
        try {
            System.out.println("---------------------演出厅2:--------------------");
            swiftDrama.perform();
        } catch (Exception e) {
        }
    }

}

输出结果:

 


 

 

 

Spring AOP中使用@Aspect注解 面向切面实现日志横切功能详解

 

 

引言:

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

       在Spring AOP中业务逻辑仅仅只关注业务本身,将日志记录,性能统计,安全控制,事务处理,异常处理等代码从业务逻辑代码中划分出来,通过对这些行为的分离,我们希望可以将它们独立到非指导业务逻辑的方法中,进而改变这些行为的时候不影响业务逻辑的代码。

相关注解介绍如下:

复制代码

 

@Aspect:作用是把当前类标识为一个切面供容器读取
 
@Pointcut:Pointcut是植入Advice的触发条件。每个Pointcut的定义包括2部分,一是表达式,二是方法签名。方法签名必须是 public及void型。可以将Pointcut中的方法看作是一个被Advice引用的助记符,因为表达式不直观,因此我们可以通过方法签名的方式为 此表达式命名。因此Pointcut中的方法只需要方法签名,而不需要在方法体内编写实际代码。
@Around:环绕增强,相当于MethodInterceptor
@AfterReturning:后置增强,相当于AfterReturningAdvice,方法正常退出时执行
@Before:标识一个前置增强方法,相当于BeforeAdvice的功能,相似功能的还有
@AfterThrowing:异常抛出增强,相当于ThrowsAdvice

复制代码

 一:引入相关依赖

  

二:Spring的配置文件 applicationContext.xml 中引入context、aop对应的命名空间;配置自动扫描的包,同时使切面类中相关方法中的注解生效,需自动地为匹配到的方法所在的类生成代理对象。

   

3、创建简单计算器的接口ArithmeticCalculator.java及实现类ArithmeticCalculatorImpl.java

复制代码

package com.svse.aop;

public interface ArithmeticCalculator {

    //定义四个简单的借口 加减乘除算法
    int add(int i, int j);

    int sub(int i, int j);

    int mul(int i, int j);

    int div(int i, int j);
}

复制代码

复制代码

package com.svse.aop;
import org.springframework.stereotype.Component;

//将实现类加入Spring的IOC容器进行管理
@Component("arithmeticCalculator")
public class ArithmeticCalculatorImpl implements ArithmeticCalculator {

    @Override
    public int add(int i, int j) {
         int result = i + j;
            return result;
    }

    @Override
    public int sub(int i, int j) {
          int result = i - j;
            return result;
    }

    @Override
    public int mul(int i, int j) {
          int result = i * j;
            return result;
    }

    @Override
    public int div(int i, int j) {
          int result = i / j;
            return result;
    }

}

复制代码

4、现在想在实现类中的每个方法执行前、后、以及是否发生异常等信息打印出来,需要把日志信息抽取出来,写到对应的切面的类中 LoggingAspect.java 中
要想把一个类变成切面类,需要两步,
① 在类上使用 @Component 注解 把切面类加入到IOC容器中
② 在类上使用 @Aspect 注解 使之成为切面类
 

复制代码

package com.svse.aop;

import java.util.Arrays;

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.springframework.stereotype.Component;

import com.tencentcloudapi.vod.v20180717.VodClient;

/**
 * 日志切面
 * 
 * @author zhaoshuiqing<br>
 * @date 2019年6月14日 下午3:03:29
 */
@Component
@Aspect
public class LoggingAspect {

    //现在想在实现类中的每个方法执行前、后、以及是否发生异常等信息打印出来,需要把日志信息抽取出来,写到对应的切面的类中 LoggingAspect.java 中 
    //要想把一个类变成切面类,需要两步, 
    //① 在类上使用 @Component 注解 把切面类加入到IOC容器中 
    //② 在类上使用 @Aspect 注解 使之成为切面类
    
    
    /**
     * 前置通知:目标方法执行之前执行以下方法体的内容 
     * @param jp
     */
    @Before("execution(* com.svse.aop.*.*(..))")
    public void beforeMethod(JoinPoint jp){
         String methodName =jp.getSignature().getName();
         System.out.println("【前置通知】the method 【" + methodName + "】 begins with " + Arrays.asList(jp.getArgs()));
    }
    
     /**
     * 返回通知:目标方法正常执行完毕时执行以下代码
     * @param jp
     * @param result
     */
    @AfterReturning(value="execution(* com.svse.aop.*.*(..))",returning="result")
    public void afterReturningMethod(JoinPoint jp, Object result){
         String methodName =jp.getSignature().getName();
         System.out.println("【返回通知】the method 【" + methodName + "】 ends with 【" + result + "】");
    }
    
      /**
     * 后置通知:目标方法执行之后执行以下方法体的内容,不管是否发生异常。
     * @param jp
     */
    @After("execution(* com.svse.aop.*.*(..))")
    public void afterMethod(JoinPoint jp){
        System.out.println("【后置通知】this is a afterMethod advice...");
    }
    
    

    /**
     * 异常通知:目标方法发生异常的时候执行以下代码
     */
    @AfterThrowing(value="execution(* com.qcc.beans.aop.*.*(..))",throwing="e")
    public void afterThorwingMethod(JoinPoint jp, NullPointerException e){
         String methodName = jp.getSignature().getName();
         System.out.println("【异常通知】the method 【" + methodName + "】 occurs exception: " + e);
    }
    
    
  /**
  * 环绕通知:目标方法执行前后分别执行一些代码,发生异常的时候执行另外一些代码
  * @return 
  */
 /*@Around(value="execution(* com.svse.aop.*.*(..))")
 public Object aroundMethod(ProceedingJoinPoint jp){
     String methodName = jp.getSignature().getName();
     Object result = null;
     try {
         System.out.println("【环绕通知中的--->前置通知】:the method 【" + methodName + "】 begins with " + Arrays.asList(jp.getArgs()));
         //执行目标方法
         result = jp.proceed();
         System.out.println("【环绕通知中的--->返回通知】:the method 【" + methodName + "】 ends with " + result);
     } catch (Throwable e) {
         System.out.println("【环绕通知中的--->异常通知】:the method 【" + methodName + "】 occurs exception " + e);
     }
     
     System.out.println("【环绕通知中的--->后置通知】:-----------------end.----------------------");
     return result;
 }*/

}

复制代码

   5、编写MainTest方法进行测试

复制代码

package com.svse.aop;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainTest {

    public static void main(String[] args) {
        
        //ClassPathXmlApplicationContext默认是加载src目录下的xml文件
        ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml"); 
        ArithmeticCalculator arithmeticCalculator =(ArithmeticCalculator) ctx.getBean("arithmeticCalculator");
        
        System.out.println(arithmeticCalculator.getClass());
        int result = arithmeticCalculator.add(3, 5);
        System.out.println("result: " + result);
        
        result = arithmeticCalculator.div(5, 0);
        System.out.println("result: " + result);
    }

}

复制代码

运行结果:

  

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

花凋忆往昔

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值