How to write an annotation/aspect to not enter a method but return null if a given condition is false?

前端 未结 2 1138
长发绾君心
长发绾君心 2021-01-26 20:20

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

2条回答
  •  执笔经年
    2021-01-26 20:41

    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
            1.8
            true
            true
            ignore
            UTF-8 
        
        
            
                
                    
                    compile
                    
                    test-compile
                
            
        
    
    

    Good example with more details, Baeldung. Official documentation.

提交回复
热议问题