1. 程式人生 > >Spring-通過xml配置實現AOP

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");
	}
}
<完>