AspectJ AOP LTW not working with dynamic loading of javaagent

前端 未结 1 1658
旧时难觅i
旧时难觅i 2020-12-21 08:08

Here is my sample non-working project.

It contains 2 modules:

  • aop-lib - Aspects used as lib. It contains the following classes
1条回答
  •  有刺的猬
    2020-12-21 08:37

    The explanation is quite simple: You are testing the weaving agent directly in class Main which is already loaded before you attach that very agent from that class. So you have to avoid classes which you like to be woven to be loaded too early. I suggest you put method myFunc() (horrible name, by the way) into another class. How about that?

    package com.aop.app;
    
    import com.aop.app.lib.Wrap;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    public class Application {
      private static final Logger logger = LoggerFactory.getLogger(Application.class);
    
      @Wrap
      public void myFunc(){
        logger.debug("inside myFunc");
      }
    
      public static void main(String[] args) {
        new Application().myFunc();
      }
    }
    

    Then in the last line of Main.main(..) you start the actual application you want woven:

    Application.main(null);
    

    This will yield the following output:

    com.aop.app.lib.WrapDef Loaded : false
    java.lang.UnsupportedOperationException: AspectJ weaving agent was neither started via '-javaagent' (preMain) nor attached via 'VirtualMachine.loadAgent' (agentMain)
    loading javaAgent aop-app/target/deploy/lib/aspectjweaver-1.9.1.jar
    loaded javaAgent aop-app/target/deploy/lib/aspectjweaver-1.9.1.jar
    com.aop.app.lib.WrapDef Loaded : false
    Loading
    07:56:21.703 [main] DEBUG com.aop.app.lib.WrapDef - before wrap
    07:56:21.716 [main] DEBUG com.aop.app.Application - inside myFunc
    07:56:21.716 [main] DEBUG com.aop.app.lib.WrapDef - after wrap
    

    P.S.: Do you really think it is easier for users of your aspect library to specify two properties on the JVM command line instead of just using -javaagent:/path/to/aspectweaver.jar? Anyway, you probably have your reasons to use dynamic weaver attachment. In a way I am kind of happy that someone uses the functionality I added to AspectJ myself a while ago. ;-)

    0 讨论(0)
提交回复
热议问题