下面展示通过注解编写aop。
package com.bean.AOP2;
public interface IEat {
public void eat();
}
package com.bean.AOP2;
public class Eat implements IEat {
@Override
public void eat(){
for(int i=0;i<1e4;i++);
System.out.println("today,i eat food!");
for(int i=0;i<1e4;i++);
}
}
通过注解编写切面:
package com.bean.AOP2;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
@Aspect
public class EatPrepare2 {
@Pointcut("execution(* com.bean.AOP2.Eat.eat(..))")
public void eat(){
}
@Before("eat()")
public void washHand(){
System.out.println("wash hand!");
}
@Before("eat()")
public void takeFood(){
System.out.println("take food!");
}
@After("eat()")
public void cleanDish(){
System.out.println("clean dish!");
}
@Around("eat()")
public void calculateEatime(ProceedingJoinPoint joinPoint){
try{
long begintime=System.currentTimeMillis();
System.out.println("begin eat!");
joinPoint.proceed();
long endtime=System.currentTimeMillis();
System.out.println("end eat!");
System.out.println("eat time is:"+(endtime-begintime));
}catch(Throwable t){
t.printStackTrace();
}
}
}
还是需要通过简单的xml配置文件来配置aop
<?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.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd">
<!--启用通过注解来定义切面 -->
<aop:aspectj-autoproxy>
</aop:aspectj-autoproxy>
<!-- 强启用的切面定义成bean -->
<bean id="eatprepare2" class="com.bean.AOP2.EatPrepare2"></bean>
<!-- 定义切点所在类的bean,调用eat.eat()时,eatprepare2的一系列方法将会被调用 -->
<bean id="eat" class="com.bean.AOP2.Eat"></bean>
</beans>
测试代码如下:
package com.bean.AOP2;
import org.springframework.context.support.FileSystemXmlApplicationContext;
public class Main {
public static void main(String[] args) {
FileSystemXmlApplicationContext context=new FileSystemXmlApplicationContext("BeanXml\\AOP3.xml");
//对于aop,必须向上转型为接口类型,所以,切点类必须实现了某个接口
IEat eat=(IEat)context.getBean("eat");
eat.eat();
context.close();
}
}
结果如下: