Spring AOP: logging and nested-methods

后端 未结 2 1849
旧时难觅i
旧时难觅i 2021-02-09 12:08

I have written a simple Spring2.5 app to demo/test AOP; specifically, I want to log the entry and exit of every method of every class in a specific package. This is what I have

2条回答
  •  南旧
    南旧 (楼主)
    2021-02-09 12:46

    If you're using Spring AOP, you must only call a method that's had an aspect applied to it via a reference returned by Spring, not through this, and I don't think you can apply pointcuts to private methods either (might be wrong on that last part). That's because Spring AOP applies the pointcuts through the proxy object, not by class rewriting (which is what AspectJ does). The benefit of that heavy restriction is that it is much easier to make it work in containers (I know from experience that Spring AOP works just fine inside Tomcat) because there's no warring over what bits are plugged in where.

    The best way of doing this is by splitting the class definition so that you never call a method via this, but if that's not possible then you can always try giving a bean a Spring-derived reference to itself:

    private HomeController self;
    @Required
    public void setSelf(HomeController self) { this.self = self; }
    
    public ModelAndView get() {
        System.out.println("In HomeController#get()...");
    
        self.somePrivateMethod();
        self.somePublicMethod();
    
        return new ModelAndView( "home" );
    }
    

    (This is pretty neat; self is a keyword in a number of languages but not Java so it's relatively easy to remember what you're using it for.)

提交回复
热议问题