Aop是Spring的核心特性之一,是面向切面编程技术。实现方式是基于代领模式的,在程序流中找到切点,可以在切点前后执行一部分代码。
使用AOP,在UserDao的save方法前后,切入程序:
UserDao
package com.dao; public class UserDao { public void save(){ System.out.println("in save"); } }
切面程序,在save方法执行前后要执行的程序:
package com.aop; import org.aspectj.lang.ProceedingJoinPoint; public class ServiceAop { public void before(){ System.out.println("in before"); } public void after(){ System.out.println("in after"); } public void around(ProceedingJoinPoint pjp) throws Throwable{ System.out.println("around in before"); pjp.proceed(); System.out.println("around in after"); } }
applicationContext.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:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd"> <bean id="userDao" class="com.dao.UserDao"></bean> <bean id="serviceAop" class="com.aop.ServiceAop"></bean> <aop:config> <aop:pointcut expression="execution(* com.dao.*.*(..))" id="cutId"/> <aop:aspect ref="serviceAop"> <aop:before method="before" pointcut-ref="cutId"/> <aop:after method="after" pointcut-ref="cutId"/> <aop:around method="around" pointcut-ref="cutId"/> </aop:aspect> </aop:config> </beans>
测试类:
package com.dao; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Test { public static void main(String[] args) { ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml"); UserDao ud=(UserDao) ac.getBean("userDao"); ud.save(); } }
原文地址:http://blog.csdn.net/liangwenmail/article/details/47618371