您想使用来自 AspectJ 的 @Around 建议并执行以下操作:
// Let subClass instances run normally...
cec.setActive(true);
letThemDoSomething("BEFORE", sbc1, sbc2, sbc3);
// Now change existing scenario...
cec.setActive(false);
letThemDoSomething("AFTER", sbc1, sbc2, sbc3);
这将输出:
BEFORE ======
SubClass1: doSomething() called.
SubClass2: doSomething() called.
SubClass3: doSomething() called.
AFTER ======
Blocking instance<1> method: my.first.spring.aop.aspectj.SubClassN#doSomething([]) !!
Blocking instance<2> method: my.first.spring.aop.aspectj.SubClassN#doSomething([]) !!
Blocking instance<3> method: my.first.spring.aop.aspectj.SubClassN#doSomething([]) !!
在下面几行中,我将描述如何通过注释实现这一点。
我也会在这里使用 Spring。它有助于使配置更快更容易。
1- 配置
工具和依赖项
Java 7、AspectJ 1.7.4、Spring 4.0.2
项目结构
pom.xml
<project ...>
<properties>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
<spring.version>4.0.2.RELEASE</spring.version>
<aspectj.version>1.7.4</aspectj.version>
</properties>
<dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- AspectJ -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${aspectj.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>${aspectj.version}</version>
</dependency>
</dependencies>
</project>
2 - 现有代码
BaseClass.java
public class BaseClass {
public void doSomething() {
}
public void say(String msg) {
System.out.println(msg);
}
}
SubClassN.java
public class SubClassN extends BaseClass {
private Integer index;
public SubClassN(Integer index) {
this.index = index;
}
@Override
public void doSomething() {
say("SubClass" + index + ": doSomething() called.");
}
public Integer getIndex() {
return index;
}
}
3 - 更改现有代码(不破坏任何内容...)
AspectJ 和它的@Around 建议来了。当调用任何doSomething 方法时,我们将首先要求AsjectJ 调用特定方法。 doSomething 可以位于 BaseClass 或其任何子类中的任何位置。
这个特殊方法被称为changeExistingScenario。它可以有任何名称。这里重要的是放在上面的注解。
关于@Around 值的一句话:
执行(* my.first.spring.aop.aspectj.BaseClass.doSomething(..))
这个表达式只是表示我们想要拦截的方法签名模式。
它会拦截 BaseClass 或子类中的任何 doSomething 方法
多少个参数,返回类型和访问修饰符。
更多详情见:http://guptavikas.wordpress.com/2010/04/15/aspectj-pointcut-expressions/
ChangeExistingCode.java
@Aspect // Mark ChangeExistingCode as the class for modifying the code
@Component
public class ChangeExistingCode {
private boolean active;
public void setActive(boolean active) {
this.active = active;
}
/**
*
* This method will be called by AspectJ anytime a `doSomething` method is called.
*
* This will give us a chance to decide whether the `doSomething` method should
* be called or not.
*
*/
@Around("execution(* my.first.spring.aop.aspectj.BaseClass.doSomething(..))")
public void changeExistingScenario(ProceedingJoinPoint joinPoint) throws Throwable {
// Is active ?
if (active) { // Yes, let doSomething() run as usual
joinPoint.proceed();
} else {// No, block doSomething() invokation
Signature s = joinPoint.getSignature();
System.out.format( //
"Blocking instance<%d> method: %s#%s(%s) !!\n", //
((SubClassN)joinPoint.getTarget()).getIndex(), //
s.getDeclaringTypeName(), //
s.getName(), //
Arrays.toString(joinPoint.getArgs()) //
);
}
}
}
4- 让所有的魔法出现......
Main.java
@Configuration // Mark the Main class as the class where Spring will find its configuration
@ComponentScan // Ask Spring to look for other components within the Main class package
@EnableAspectJAutoProxy // Let Spring auto configure AspectJ aspects for us...
public class Main {
private static int subClassCounter;
public static void main(String[] args) {
subClassCounter=0;
GenericApplicationContext context = new AnnotationConfigApplicationContext(Main.class);
SubClassN sbc1 = context.getBean(SubClassN.class);
SubClassN sbc2 = context.getBean(SubClassN.class);
SubClassN sbc3 = context.getBean(SubClassN.class);
ChangeExistingCode cec = context.getBean(ChangeExistingCode.class);
// Let subClass instances run normally...
cec.setActive(true);
letThemDoSomething("BEFORE", sbc1, sbc2, sbc3);
// Now change existing scenario...
cec.setActive(false);
letThemDoSomething("AFTER", sbc1, sbc2, sbc3);
context.close();
}
private static void letThemDoSomething(String prefix, SubClassN... existingClasses) {
System.out.format("%s ======\n", prefix);
for (SubClassN subClassInstance : existingClasses) {
subClassInstance.doSomething();
}
System.out.println();
}
@Bean // Tell Spring to use this method for creating SubClassN instances
@Scope(BeanDefinition.SCOPE_PROTOTYPE) // Scope prototype force creation of multiple instances
private static SubClassN buildSubClassN() {
subClassCounter++;
return new SubClassN(subClassCounter);
}
}
输出
BEFORE ======
SubClass1: doSomething() called.
SubClass2: doSomething() called.
SubClass3: doSomething() called.
AFTER ======
Blocking instance<1> method: my.first.spring.aop.aspectj.SubClassN#doSomething([]) !!
Blocking instance<2> method: my.first.spring.aop.aspectj.SubClassN#doSomething([]) !!
Blocking instance<3> method: my.first.spring.aop.aspectj.SubClassN#doSomething([]) !!
5- 参考文献