Spring中基于注解的AOP

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;

@Aspect
public 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");;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值