源碼結構:css
package com.spring.aop; /** * 談戀愛接口 * * @author Administrator * */ public interface Love { /* * 談戀愛方法 */ void fallInLove(); }
package com.spring.aop; /** * 人對象 * @author luwenbin006@163.com * */ public class Person implements Love { /* * 重寫談戀愛方法 * @see com.spring.aop.Love#fallInLove() */ public void fallInLove() { System.out.println("談戀愛了..."); } }
package com.spring.aop; import java.lang.reflect.Method; import org.springframework.aop.AfterReturningAdvice; import org.springframework.aop.MethodBeforeAdvice; /** * aop通知類 * @author luwenbin006@163.com * */ public class LoveHelper implements MethodBeforeAdvice, AfterReturningAdvice { //調用方法以前執行 public void before(Method mtd, Object[] arg1, Object arg2) throws Throwable { System.out.println("談戀愛以前必需要彼此瞭解!"); } //調用方法以後執行 public void afterReturning(Object arg0, Method arg1, Object[] arg2, Object arg3) throws Throwable { System.out.println("咱們已經談了5年了,最終仍是分手了!"); // System.out.println("咱們已經談了5年了,最終步入告終婚的殿堂!"); } }
<?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:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"> <!-- 配置bean --> <bean id="person" class="com.spring.aop.Person"> </bean> <!-- 配置通知方法類 --> <bean id="loveHelper" class="com.spring.aop.LoveHelper"> </bean> <!-- 聲明advisor 指定哪些方法通知哪一個類 --> <bean id="loveHelperAdvisor" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor"> <property name="advice" ref="loveHelper" /> <property name="pattern" value=".*fallInLove" /> </bean> <!-- 自動代理建立模式 --> <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" /> </beans>
package com.spring.aop; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.spring.aop.Love; /** * aop測試方法類 * @author luwenbin006@163.com * */ public class LoveTest { public static void main(String[] args) { //加載spring配置文件 ApplicationContext appCtx = new ClassPathXmlApplicationContext( "applicationContext.xml"); //獲得person對象 Love love = (Love) appCtx.getBean("person"); //調用談戀愛方法 love.fallInLove(); } }
七、源碼下載地址:源碼下載html