首页 | 联系我们 | 叶凡网络官方QQ群:323842844
游客,欢迎您! 请登录 免费注册 忘记密码
您所在的位置:首页 > 开发语言 > Java开发 > 正文

AOP中的after/before advice

作者:cocomyyz 来源: 日期:2013-08-04 23:25:12 人气:89 加入收藏 评论:0 标签:java

after advice

=========================================


IHello.java


package aop;

public interface IHello {
public void hello();

}


Hello.java


package aop;

public class Hello implements IHello {
private String message;

public void hello() {
  System.out.println("Hello." + message);
}

public String getMessage() {
  return message;
}

public void setMessage(String message) {
  this.message = message;
}
}


AfterAdvice.java


package aop;


public class AfterAdvice {


public void myAfter() {
  System.out.println("insert my log");
}
}


Test.java


package aop;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {

public static void main(String[] args) {
  ApplicationContext cxt = new ClassPathXmlApplicationContext("applicationContext.xml");
  IHello hello = (IHello)cxt.getBean("hello");
  hello.hello();
}


}


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-2.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">


<bean id="hello" class="aop.Hello">
  <property name="message" value="Hello world."></property>
</bean>

<bean id="afterAdvice" class="aop.AfterAdvice">
</bean>

<aop:config>
  <aop:aspect id="myLogAdvice" ref="afterAdvice">
   <aop:after
    pointcut="execution(* aop.IHello.*(..))"
    method="myAfter"/>
  </aop:aspect>
</aop:config>
</beans>



before advice

=====================================

只要将配置中的after改成before就行了




=========================================================

或者将

<aop:config>
  <aop:aspect id="myLogAdvice" ref="afterAdvice">
   <aop:after
    pointcut="execution(* aop.IHello.*(..))"
    method="myAfter"/>
  </aop:aspect>
</aop:config>

改成

<aop:aspectj-autoproxy></aop:aspectj-autoproxy>


然后用注解:

package aop;

import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;

@Aspect
public class AfterAdvice {

@After("execution(* aop.IHello.*(..))")
public void myAfter() {
  System.out.println("insert my log");
}
}


================================

当然before也就是将@After改成@Before


本文网址:http://www.mingyangnet.com/html/java/151.html
读完这篇文章后,您心情如何?
  • 0
  • 0
  • 0
  • 0
  • 0
  • 0
  • 0
  • 0
上一篇: java试题整理
更多>>网友评论
发表评论
编辑推荐
  • 没有资料