Sunday 15 March 2015

java - Injected bean becomes null after using AOP -



java - Injected bean becomes null after using AOP -

i using spring4 along spring boot.

before tired utilize aop, bean(commandservice),which used in controller, auto injected well, after tired utilize aop collect debug message, bean becomes null!

here application.java

@configuration @enableautoconfiguration @componentscan({"hello","wodinow.weixin.jaskey"}) public class application extends { public static void main(string[] args) { applicationcontext ctx = springapplication.run(application.class, args); logutil.info("beans provided spring boot:"); string[] beannames = ctx.getbeandefinitionnames(); arrays.sort(beannames); (string beanname : beannames) { logutil.info(beanname); } logutil.info("application boots completes!"); } @bean public commandservice commandservice(){ logutil.debug("commandservice.getinstance()"+ commandservice.getinstance()) ;//here indeed see spring executes , returns object when application boots homecoming commandservice.getinstance();//this returns singleton instance }

}

my controller throws null pointer:

@controller public class corecontroller { @autowired commandservice commandservice;//here service null after using aop //...some request methods }

the aspect added now:

//if comment out these 2 annoations, bean auto injected @aspect @component public class logaspect { @pointcut("execution(* wodinow.weixin.jaskey..*.*(..))") private void debug_log(){}; @around("debug_log()") public void debug(proceedingjoinpoint joinpoint) throws throwable{ logutil.debug("enter "+joinpoint.getsignature()); try{ joinpoint.proceed(); logutil.debug("returns "+joinpoint.getsignature()); } catch(throwable t){ logutil.error(t.getmessage()+"occurs in "+joinpoint.getsignature(),t); throw t; } } }

i new spring, can help me this?

your @componentscan trying resolve , autowire dependencies corecontroller. when tries resolve dependency finds @bean in application class. tries resolve dependency calling application.commandservice(). when method called, sees matching @pointcut , invokes advice method. since @advice not returning anything, callers see nil returned, , that resolution of dependency returned null.

the prepare here alter @around advice homecoming value of invocation.

@around("debug_log()") public object debug(proceedingjoinpoint joinpoint) throws throwable{ logutil.debug("enter "+joinpoint.getsignature()); try{ // homecoming invocation homecoming joinpoint.proceed(); } catch(throwable t){ logutil.debug(t.getmessage()+"occurs in "+joinpoint.getsignature(),t); throw t; } }

java spring spring-mvc spring-boot spring-aop

No comments:

Post a Comment