Spring顾问和注解

一,顾问包装通知

通知(advice)是Spring中的一种比较简单的切面,只能将切面织入到目标类的所有方法中,而无法对指定方法进行增强

顾问(advisor)是Spring提供的另外一种切面,可以织入到指定的方法中  接口 PointcutAdvisor

实现类:NameMatchMethodPointcutAdvisor(基于方法名称的增强顾问),RegexpMethodPointcutAdvice(基于正则表达式的增强顾问)

  以上文件使用的是NameMatchMethodPointcutAdvisor,当然也可替换成为 RegExpMethodPonitcutAdvisor,基于正则表达式通配方法名的顾问,可配置性更加优良。

二,顾问代理生成器

  顾问代理生成器主要分两种

          自动顾问代理生成器:DefaultAdvisorAutoProxyCreator

          名称顾问代理生成器:BeanNameAutoProxyCreator

 

 

 名称顾问代理生成器也可以替换成自动顾问代理生成器,自动顾问代理生成器默认为Spring中所有的Bean对象创建代理 无需使用ID注入

三,注解

  IOC:

               @Component:实现Bean组件的定义

               @Repository:用于标注DAO类,功能与@Component作用相当

               @Service:用于标注业务类

               @Controller:用于标注控制器

   DI:

               @Resource(name="userService")  默认ByName方式,如果name确实默认按照ByType方式注入

               @Autowired  默认ByType方式,如果出现同名类,则不能按照Type进行注入  需要使用@Qualifier 指明ID                          

  AOP:

              @Aspect 声明切面

              @Ponitcut 声明公共的切点表达式

              @Before 前置增强

              @AfterReturning 后置增强

              @Around 环绕增强

              @AfterThrowing 异常抛出增强

              @After 最终增强

注解实现增强

@Aspect
@Component
public class Advices {
    //设定切入点表达式
    @Pointcut("execution(* *..aop.*.*(..))")
    public  void  Pointcut(){

    }

    //前置增强
    @Before("Pointcut()")
    public void before(){
        System.out.println("=======前置=========");
    }

    //后置增强
    @AfterReturning("Pointcut()")
    public  void afterReturning(){
        System.out.println("=======后置==========");
    }

    //环绕增强
    @Around("Pointcut()")
    public Object Around(ProceedingJoinPoint jp) throws Throwable {

        System.out.println("=======环绕前==========");
        Object proceed = jp.proceed();
        System.out.println("=======环绕后==========");
        return proceed;
    }

    //异常增强
    @AfterThrowing(pointcut = "execution(* *..aop.*.*(..))",throwing = "ex")
    public void AfterThrowing(Exception ex){
        System.out.println("发生异常");
    }

    //最终增强
    @After("Pointcut()")
    public void After(){
        System.out.println("=======最终增强=========");
    }
}

 

 

               

原文地址:https://www.cnblogs.com/liuying23/p/11775843.html