1.自定义创建一个类,类中有两个方法
package com. lixv. log;
public class DiyPointCut {
public void diyBefore ( ) {
System. out. println ( "方法执行前===============" ) ;
}
public void diyAfter ( ) {
System. out. println ( "方法执行后===============" ) ;
}
}
2.在beans.xml中引入aop
< 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"
xmlns: context= " http://www.springframework.org/schema/context"
xsi: schemaLocation= " http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd" >
3.在beans.xml中定义bean,并使用aop来实现aop操作
< bean id = " userService" class = " com.lixv.service.UserServiceImpl" />
< bean id = " diyPointCut" class = " com.lixv.log.DiyPointCut" />
< aop: config>
< aop: aspect ref = " diyPointCut" >
< aop: pointcut id = " point" expression = " execution(* com.lixv.service.UserServiceImpl.*(..))" />
< aop: before method = " diyBefore" pointcut-ref = " point" />
< aop: after method = " diyAfter" pointcut-ref = " point" />
</ aop: aspect>
</ aop: config>
aop:aspect的ref属性指向切面(一个类,即我们第一步创建的类)。 aop:pointcut配置需要加日志的方法 aop:before的method指向切面中的一个方法,在aop:pointcut指向的方法执行之前调用 aop:after的method指向切面中的一个方法,在aop:pointcut指向的方法执行之后调用
4.测试
@Test
public void test2 ( ) {
ApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext ( "beans.xml" ) ;
UserService userService = ( UserService) classPathXmlApplicationContext. getBean ( "userService" ) ;
userService. add ( 5 ) ;
}
5.运行结果
6.注意
这种实现没有第一种方法(通过继承spring中的接口实现的方法)厉害,不能够获取目标方法的反射等信息。