Spring AOP 两种注入方式
第一种是基于annotation方式注入
(1)定义一个Aspect对象LogBeforeAdvice
package org.aop;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
@Aspect
public class LogBeforeAdvice {
private Logger logger = Logger.getLogger(this.getClass().getName());
@Pointcut("execution(* org.aop.IHello.*(..))")
private void logging(){}
@Before("logging()")
public void before(JoinPoint joinPoint){
logger.log(Level.INFO,"method start ..." + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
}
@AfterReturning(pointcut="logging()" ,returning="retVal")
public void afterReturning(JoinPoint joinPoint ,Object retVal){
logger.log(Level.INFO,"method end ..." + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
}
}
(2)定义一个接口类IHello
package org.aop;
public interface IHello {
public void hello(String hello);
}
(3)定义一个实现类HelloSpeaker
package org.aop;
public class HelloSpeaker implements IHello {
public void hello(String hello) {
System.out.println("你好! " + hello);
}
}
(4)配置Spring配置文件
<?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="logBeforeAdvice" ref="logBeforeAdvice">
<aop:pointcut id="helloLog" expression="execution(* org.aop.IHello.*(**))"/>
<aop:before
pointcut-ref="helloLog"
method="before"
/>
<aop:after-returning
pointcut-ref="helloLog"
method="afterReturning"
/>
</aop:aspect>
</aop:config >
执行结果是一样的