Spring中基于注解的AOP

来源:互联网 发布:淘宝客户vip设置 编辑:程序博客网 时间:2024/06/05 06:47

Spring提供了基于注解的AOP。

开启配置:在配置文件中配置

<aop:aspectj-autoproxy></aop:aspectj-autoproxy>

前置通知

切点类

package cn.belle.test;public class HelloWorldService {public void sayBefore(String param) {System.out.println("我是前置通知"+param);}}

切面类

package cn.belle.test;import org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.annotation.Before;import org.aspectj.lang.annotation.Pointcut;@Aspectpublic class HelloAspect {@Pointcut(value = "execution(* cn.belle..*.sayBefore(..)) && args(param)", argNames = "param")public void pointcut(String param) {}@Before(value = "pointcut(param)", argNames = "param")public void beforeAdvice(String param) {System.out.println("我是前置通知的通知方法" + param);}}

可以看见首先切面类要注解为@Aspect,引入一个方法 pointcut 来连接切点与切面

@Pointcut : value代表切入点表达式,argNames代表用于匹配通知方法中的同名参数

@Before 声明前置通知  value代表切入点过渡方法名称

将2个类配置到Spring配置文件中

<bean id="helloWorldService" class="cn.belle.test.HelloWorldService" /><bean id="aspect" class="cn.belle.test.HelloAspect" />

测试类

import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import cn.belle.test.HelloAspect;import cn.belle.test.HelloWorldService;public class Test {public static void main(String[] args) {ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");HelloWorldService helloWorldService = (HelloWorldService) ctx.getBean("helloWorldService");helloWorldService.sayBefore("before");;}}


0 0
原创粉丝点击