spring 学习3-Spring AOP
Using @AspectJ-Style Annotations
@Component("myDependency") public class MyDependency { public void foo(int intValue) { System.out.println("foo(int): " + intValue); } public void bar() { System.out.println("bar()"); } }
?
@Component("myBean") public class MyBean { private MyDependency myDependency; public void execute() { myDependency.foo(100); myDependency.foo(101); myDependency.bar(); } @Autowired public void setDep(MyDependency myDependency) { this.myDependency = myDependency; } }
?
@Component @Aspect public class MyAdvice { @Pointcut("execution(* com.apress.prospring3.ch7..foo*(int)) && args(intValue)") public void fooExecution(int intValue) { } @Pointcut("bean(myDependency*)") public void inMyDependency() { } @Before("fooExecution(intValue) && inMyDependency()") public void simpleBeforeAdvice(JoinPoint joinPoint, int intValue) { // Execute only when intValue is not 100 if (intValue != 100) { System.out.println("Executing: " + joinPoint.getSignature().getDeclaringTypeName() + " " + joinPoint.getSignature().getName() + " argument: " + intValue); } } @Around("fooExecution(intValue) && inMyDependency()") public Object simpleAroundAdvice(ProceedingJoinPoint pjp, int intValue) throws Throwable { System.out.println("Before execution: " + pjp.getSignature().getDeclaringTypeName() + " " + pjp.getSignature().getName() + " argument: " + intValue); Object retVal = pjp.proceed(); System.out.println("After execution: " + pjp.getSignature().getDeclaringTypeName() + " " + pjp.getSignature().getName() + " argument: " + intValue); return retVal; } }
?
<aop:aspectj-autoproxy/> <!--inform Spring to scan for @AspectJ-style annotations--><context:component-scan base-package="com.apress.prospring3.ch7.aspectjannotation"/>
?