1、IDEA下新建maven项目
项目目录
2、编写Func类,其中随便添加两个方法
package com.aop;
public class Func {
public void add(){
System.out.println("做点事情吧");
}
public void test(){
System.out.println("这是一个测试方法");
}
}
3、编写FuncPlus类,这是对Func类中方法的增强类
package com.aop;
public class FuncPlus {
public void before(){
System.out.println("开始前搞点事情");
}
public void after(){
System.out.println("结束再搞点事情");
}
}
4、编写配置文件beans.xml,通过xml配置文件,找出需要增强的方法并织入其中
<?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/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">
<!-- bean定义与aop配置 -->
<bean id="func" class="com.aop.Func"></bean>
<bean id="funcPlus" class="com.aop.FuncPlus"></bean>
<!--配置aop操作-->
<aop:config>
<!--配置切入点,这里默认对Func类的所有方法增强,当然也可以增强单个方法,只需要修改路径就行-->
<aop:pointcut id="point" expression="execution(* com.aop.Func.*())" ></aop:pointcut>
<!--配置切面 把增强用到方法后面-->
<aop:aspect ref="funcPlus">
<!--配置增强类,method为增强类中哪个方法为前置-->
<aop:before method="before" pointcut-ref="point"></aop:before>
</aop:aspect>
<aop:aspect ref="funcPlus">
<!--配置增强类,method为增强类中哪个方法为前置-->
<aop:after method="after" pointcut-ref="point"></aop:after>
</aop:aspect>
</aop:config>
</beans>
5、编写测试类
package com.aop;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestDemo {
public static void main(String[] args) {
ApplicationContext context=new ClassPathXmlApplicationContext("beans.xml");
Func lock=(Func)context.getBean("func");
lock.test();
}
}
6、测试结果