Spring 进阶(15)Spring的AOP(3) 使用注解配置切面(1) 方法执行和方法执行之后的增强处理

52 篇文章 0 订阅
  1. 前面讲的是使用AspectJ来实现AOP编程,这里的例子是在spring框架通过aspectJ实现AOP编程。
  2. 要继续往下看需要你把aspectJ先装好,怎么装在进阶(15)有介绍。
  3. 在安装好aspctJ之后,把安装目录下lib文件夹下的aspectjrt.jar和aspectjweaver.jar添加为lib,怎么添加就不仔细说了哈。
  4. 代码呀代码,这里呢是实现在运行Hello的hello方法之前调用AutoAspect的before方法。
    1. 一个一个讲解,首先是beans.xml.在beans.xml中导入了aop支持,并且使用注解来配置bean和annontationd。
      <?xml version="1.0" encoding="GBK"?>
      <!--要导入zop支持-->
      <beans xmlns="http://www.springframework.org/schema/beans"
      	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      	xmlns:context="http://www.springframework.org/schema/context"
      	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.0.xsd
      	http://www.springframework.org/schema/context
      	http://www.springframework.org/schema/context/spring-context-4.0.xsd
      	http://www.springframework.org/schema/aop
      	http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">
      	<!-- 指定自动搜索Bean组件、自动搜索切面类 -->
      	<context:component-scan base-package="before_package">
      		<context:include-filter type="annotation"
      			expression="org.aspectj.lang.annotation.Aspect"/>
      	</context:component-scan >
      	<!-- 启动@AspectJ支持 -->
      	<aop:aspectj-autoproxy/>
      </beans>
      

      Hello,一个普通的类,要注意的是它并不知道自己在执行的过程中有被增强了。

      package before_package;
      
      import org.springframework.stereotype.Component;
      
      @Component("hello")
      public class Hello {
          public void sayHello(String  a, String b){
              System.out.println(a + " ," + b);
          }
      }
      

      然后是使用了@Aspect注解的类,用法和使用Aspect差不多,指定对那些类的哪些方法进行如何的增强 

      @Aspect
      public class AuthAspect {
          @After("execution(* before_package.*.*(..))")
          public void before(){
              System.out.println("before");
          }
      }

      测试类

      package test_spring_aop_package;
      
      import before_package.Hello;
      import org.springframework.context.ApplicationContext;
      import org.springframework.context.support.ClassPathXmlApplicationContext;
      
      public class SpringTest {
          public static void main(String []args){
              ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
              Hello hello = applicationContext.getBean("hello", Hello.class);
              hello.sayHello();
          }
      
      }
      

      还有就是在方法执行之后的增强处理,就是把Before换成After就好了,原理是一样的,就不贴代码了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值