I currently have a requirement where I need to return null from 100s of methods if a given condition is false. I was thinking of using Java Annotations or Spring Aspects for thi
Without spring you could use pure AspectJ:
Demo.java : example of the method we want to modify
public class Demo {
public String boom(String base) {
return base;
}
}
DemoAspect.aj : configuration file. Getting started. In AspectJ, pointcuts pick out certain join points in the program flow. To actually implement crosscutting behavior, we use advice. Advice brings together a pointcut (to pick out join points) and a body of code (to run at each of those join points): before, around, after...
public aspect DemoAspect {
pointcut callBoom(String base, Demo demo) :
call(String Demo.boom(String)) && args(base) && target(demo);
String around(String base, Demo demo) : callBoom(base, demo){
if ("detonate".equals(base)) {
return "boom!";
} else {
return proceed(base, demo);
}
}
}
DemoTest.java
public class DemoTest {
@Test
void name() {
Demo demo = new Demo();
assertEquals("boom!", demo.boom("detonate"));
assertEquals("fake", demo.boom("fake"));
}
}
Add dependencies into pom.xml
org.aspectj
aspectjrt
1.8.13
org.aspectj
aspectjweaver
1.8.13
And plugin, pay attention to the versions. For example 1.11 plugin expects 1.8.13 libraries.
org.codehaus.mojo
aspectj-maven-plugin
1.11
1.8
1.8
true
true
ignore
UTF-8
compile
test-compile
Good example with more details, Baeldung. Official documentation.