我目前有一个要求,如果给定条件为false,则需要从100多个方法中返回null。我当时在考虑使用Java注释或Spring Aspects,这样就不必在各处编写if-else代码块。关于如何使用Java注释或Spring Aspects做到这一点的任何想法吗?
任何指针都可能有用。
答案 0 :(得分:0)
如果我对您的理解正确,那么您需要Spring @Conditional
注释。
您创建一些实现Spring的Condition
接口的公共类:
public class Test implements Condition {
...
}
然后,将上述注释与带参数的参数一起使用,该参数以公共类作为参数。
@Conditional(Test.class)
public Object someMethod(boolean context){
/*and so do some logics; if the value of 'context' variable is false, you can return
null; otherwise, just return like this*/
return new someMethodImpl1();
}
希望我能帮上忙。我很高兴进行任何更正。干杯!
答案 1 :(得分:0)
没有春天,您可以使用纯AspectJ:
Demo.java:我们要修改的方法示例
public class Demo {
public String boom(String base) {
return base;
}
}
DemoAspect.aj:配置文件。 autocorrelation。在AspectJ中,Getting started选择程序流程中的某些连接点。为了实际实现横切行为,我们使用建议。 pointcuts汇集了一个切入点(以选择连接点)和一段代码(在每个连接点处运行):在...之前,周围,之后...
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"));
}
}
将依赖项添加到pom.xml
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.8.13</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.13</version>
</dependency>
和插件,请注意版本。例如1.11插件需要1.8.13库。
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>aspectj-maven-plugin</artifactId>
<version>1.11</version>
<configuration>
<complianceLevel>1.8</complianceLevel>
<source>1.8</source>
<target>1.8</target>
<showWeaveInfo>true</showWeaveInfo>
<verbose>true</verbose>
<Xlint>ignore</Xlint>
<encoding>UTF-8 </encoding>
</configuration>
<executions>
<execution>
<goals>
<!-- use this goal to weave all your main classes -->
<goal>compile</goal>
<!-- use this goal to weave all your test classes -->
<goal>test-compile</goal>
</goals>
</execution>
</executions>
</plugin>