spring aop示例

来源:互联网 发布:vba实时抓取网页数据 编辑:程序博客网 时间:2024/04/30 14:47

示例目录结构如下:



Login.java

package com.li.common;public class Login {public void login() {System.out.println("login...");}}

Check.java

package com.li.aspect;import org.aspectj.lang.ProceedingJoinPoint;public class Check {public void before() {System.out.println("before");}public void afterReturningExample() {System.out.println("afterReturning");} public void afterThrowingExample() {System.out.println("afterThrowing");} public void afterFinallyExample() {System.out.println("afterFinally");}public void aroundExample(ProceedingJoinPoint pjp) throws Throwable{pjp.proceed();   System.out.println("around");} }

Test.java

package com.li.tes;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import com.li.common.Login;public class Test {public static void main(String[] args) {ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");Login login = (Login) ac.getBean("login");login.login();}}

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:aop="http://www.springframework.org/schema/aop"      xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"><aop:config>  <aop:aspect id="myAspect" ref="check" >   <aop:pointcut id="myPointcut"  expression="execution(* com.li.common.Login.login(..))"/>   <aop:before pointcut-ref="myPointcut" method="before"/>   <aop:after-returning  pointcut-ref="myPointcut"   method="afterReturningExample"/>  <aop:after-throwing  pointcut-ref="myPointcut"  method="afterThrowingExample"/>  <aop:after  pointcut-ref="myPointcut"   method="afterFinallyExample"/>  <aop:around    pointcut-ref="myPointcut"    method="aroundExample"/>    </aop:aspect></aop:config><bean class="com.li.aspect.Check" name="check"/><bean class="com.li.common.Login" name="login"/></beans>


注:execution(* com.li.common.Login.login(..)) *号指方法的返回值类型,..指任意参数个数


原创粉丝点击