Spring-通过xml配置实现AOP

1.定义切面类

如下函数,将beforeMethod应用到其他函数中。

package test;

import org.aspectj.lang.JoinPoint;

public class LoggingAspect {
	public void beforeMethod(JoinPoint joinPoint){
		String methodName = joinPoint.getSignature().getName();
		System.out.println(methodName + " begins.");
	}
}

2.定义配置文件

如下所示,分别定义person和loggingAspect的bean,然后定义一个aop:config把他们两个关联起来即可。

这里仅定义了前置通知作为实例,其他的通知都是类似的。另外,Person类过于简单,实现省略掉了。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
	<bean id="person" class="test.Person"></bean>
	
	<!-- 配置切面的bean -->
	<bean id="loggingAspect" class="test.LoggingAspect"></bean>
	
	<!-- 建立切面关联 -->
	<aop:config>
		<aop:pointcut expression="execution(public void test.Person.setName(String))" id="setNamePointcut"/>
		<aop:aspect ref="loggingAspect" order="1">
			<aop:before method="beforeMethod" pointcut-ref="setNamePointcut"/>
		</aop:aspect>
	</aop:config>
</beans>

3.测试类

这里setName调用时,就会执行切面函数。

public class MainTest {
	public static void main(String[] args) {
		ApplicationContext ctx = new ClassPathXmlApplicationContext("aopconfig.xml");
		Person person = ctx.getBean("person", Person.class);
		person.setName("high");
	}
}
<完>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值