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