Announcement Announcement Module
Collapse
No announcement yet.
Basic AOP not working Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Basic AOP not working

    Hi,
    am a newbie to AOP and experimenting with it. But i dont know whats wrong with the below snippet. the profiler code is not getting executed

    xml config:

    Code:
    	<aop:aspectj-autoproxy/>
    	
    	<bean id="profiler" class="com.capcvs.aop.advices.SimpleProfiler"/>
    	
    	<aop:config>
    		<aop:aspect ref="profiler">
    			<aop:pointcut id="anyTaskMethod"
    				expression="execution(* com.capcvs.web.controller.task.TaskController.handleListAllTasks(..))"/>
    			<aop:around pointcut-ref="anyTaskMethod"
    			method="profile"/>
    		</aop:aspect>
    	</aop:config>
    task controller (this extends MultiActionController.. )

    Code:
    		<bean id="taskController" class="com.capcvs.web.controller.task.TaskController">
    		<property name="methodNameResolver">
    			<bean class="org.springframework.web.servlet.mvc.multiaction.PropertiesMethodNameResolver">
    				<property name="mappings">
    					<props>
    						<prop key="/listalltasks.htm">handleListAllTasks</prop>
    						<prop key="/taskdetail.htm">handleGetTaskDetail</prop>
    						<prop key="/owntask.htm">handleOwnTask</prop>
    						<prop key="/listmytasks.htm">handleListMyTasks</prop>
    					</props>
    				</property>
    			</bean>
    		</property>
    		<property name="taskBO" ref="taskBO"/>
    		<property name="userBO" ref="userBO"/>
    	</bean>
    simpleprofiler
    Code:
    package com.capcvs.aop.advices;
    import org.aspectj.lang.ProceedingJoinPoint;
    import org.aspectj.lang.annotation.Aspect;
    import org.springframework.util.StopWatch;
    @Aspect
    public class SimpleProfiler {
    	public Object profile(ProceedingJoinPoint call) throws Throwable {
    		StopWatch clock = new StopWatch(
    				"Profiling some txn");
    		try {
    			clock.start(call.toShortString());
    			return call.proceed();
    		} finally {
    			clock.stop();
    			System.out.println(clock.prettyPrint());
    		}
    	}
    }
    thanks,
    sreedhar.

  • #2
    Spring AOP can only intercept methods which are called from outside the object (i.e., through the proxy which Spring generates around the object). In the case of Spring MVC controllers, only the the handleRequest() method is generally called from outside the object. Other methods, such as the handleListAllTasks() method in your example, are invoked internally within the object by base class method(s), and will not pass through the AOP proxy. The following section in the reference documentation talks about this in more detail:

    http://static.springframework.org/sp...ng-aop-proxies

    If you want to use Spring AOP with your controller, you may need to define your pointcut expression to match the handleRequest() method of the Controller interface instead of your application-specific controller method. Other alternatives would be to use AspectJ, or have your controller method delegate to another Spring-managed object where the profiling advice is applied.

    One other comment is that it appears you're using a mix of annotation-based and schema-based AOP configuration in your example. If you configure the aspect in your application context with an <aop:config> section, you don't need to annotate your advice class with @Aspect.

    Comment


    • #3
      Hey Mike!
      Thanks for the valuable info!
      i tried this stuff with some other POJO and it worked. Also i noticed that i had to put logger.info(..) and not System.out.println(clock.prettyPrint()) in the profiler.
      But even when i change the profile as below the method is not being interceptedi tried it with the 'execution' PCD as well)
      Code:
      	<aop:config>
      		<aop:aspect ref="profiler">
      			<aop:pointcut id="anyTaskMethod"
      				expression="within(com.capcvs.web.controller.task.*)"/>
      			<aop:around pointcut-ref="anyTaskMethod"
      			method="profile"/>
      		</aop:aspect>
      	</aop:config>
      Here is the debug info from the log:
      Code:
      2007-11-25 21:30:10,234 DEBUG [org.springframework.web.servlet.DispatcherServlet] - Last-Modified value for [/capcvs/listmytasks.htm] is [-1]
      2007-11-25 21:30:10,234 DEBUG [org.springframework.web.servlet.DispatcherServlet] - DispatcherServlet with name 'capcvs' received request for [/capcvs/listmytasks.htm]
      2007-11-25 21:30:10,234 DEBUG [org.springframework.web.servlet.DispatcherServlet] - Bound request context to thread: org.acegisecurity.wrapper.SavedRequestAwareWrapper@1b68215
      2007-11-25 21:30:10,234 DEBUG [org.springframework.web.servlet.DispatcherServlet] - Testing handler adapter [org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter@13e8c1c]
      2007-11-25 21:30:10,234 DEBUG [org.springframework.web.servlet.DispatcherServlet] - Testing handler adapter [org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter@b8705b]
      2007-11-25 21:30:10,234 DEBUG [org.springframework.web.servlet.mvc.multiaction.PropertiesMethodNameResolver] - Returning handler method name 'handleListMyTasks' for lookup path: /listmytasks.htm
      2007-11-25 21:30:10,234 DEBUG [org.springframework.orm.hibernate3.SessionFactoryUtils] - Opening Hibernate Session
      2007-11-25 21:30:10,265 DEBUG [org.springframework.orm.hibernate3.HibernateTemplate] - Eagerly flushing Hibernate session
      2007-11-25 21:30:10,281 DEBUG [org.springframework.orm.hibernate3.SessionFactoryUtils] - Closing Hibernate Session
      2007-11-25 21:30:10,328 DEBUG [org.springframework.beans.CachedIntrospectionResults] - Getting BeanInfo for class [com.capcvs.web.filter.UserTaskFilter]
      2007-11-25 21:30:10,328 DEBUG [org.springframework.beans.CachedIntrospectionResults] - Caching PropertyDescriptors for class [com.capcvs.web.filter.UserTaskFilter]
      2007-11-25 21:30:10,328 DEBUG [org.springframework.beans.CachedIntrospectionResults] - Found bean property 'class' of type [java.lang.Class]
      2007-11-25 21:30:10,328 DEBUG [org.springframework.beans.CachedIntrospectionResults] - Found bean property 'taskId' of type [java.lang.Integer]
      2007-11-25 21:30:10,328 DEBUG [org.springframework.beans.factory.support.DefaultListableBeanFactory] - Returning cached instance of singleton bean 'myTasksView'
      2007-11-25 21:30:10,328 DEBUG [org.springframework.web.servlet.view.ResourceBundleViewResolver] - Cached view [myTasksView_en_US]
      2007-11-25 21:30:10,328 DEBUG [org.springframework.web.servlet.DispatcherServlet] - Rendering view [org.springframework.web.servlet.view.JstlView: name 'myTasksView'; URL [/WEB-INF/views/jsp/countries/model.jsp]] in DispatcherServlet with name 'capcvs'
      2007-11-25 21:30:10,328 DEBUG [org.springframework.web.servlet.view.JstlView] - Rendering view with name 'myTasksView' with model {myTasks=[email protected]4e0, org.springframework.validation.BindingResult.myTasks=org.springframework.validation.BeanPropertyBindingResult: 0 errors} and static attributes {content=../task/mytasks.jsp, nav=nav.jsp, htitle=home.htitle}
      2007-11-25 21:30:10,328 DEBUG [org.springframework.web.servlet.view.JstlView] - Added model object 'content' of type [java.lang.String] to request in view with name 'myTasksView'
      2007-11-25 21:30:10,328 DEBUG [org.springframework.web.servlet.view.JstlView] - Added model object 'rc' of type [org.springframework.web.servlet.support.RequestContext] to request in view with name 'myTasksView'
      2007-11-25 21:30:10,328 DEBUG [org.springframework.web.servlet.view.JstlView] - Added model object 'myTasks' of type [org.springframework.beans.support.RefreshablePagedListHolder] to request in view with name 'myTasksView'
      2007-11-25 21:30:10,328 DEBUG [org.springframework.web.servlet.view.JstlView] - Added model object 'nav' of type [java.lang.String] to request in view with name 'myTasksView'
      2007-11-25 21:30:10,328 DEBUG [org.springframework.web.servlet.view.JstlView] - Added model object 'org.springframework.validation.BindingResult.myTasks' of type [org.springframework.validation.BeanPropertyBindingResult] to request in view with name 'myTasksView'
      2007-11-25 21:30:10,328 DEBUG [org.springframework.web.servlet.view.JstlView] - Added model object 'htitle' of type [java.lang.String] to request in view with name 'myTasksView'
      2007-11-25 21:30:11,875 DEBUG [org.springframework.web.servlet.view.JstlView] - Forwarded to resource [/WEB-INF/views/jsp/countries/model.jsp] in InternalResourceView 'myTasksView'
      2007-11-25 21:30:11,875 DEBUG [org.springframework.web.servlet.DispatcherServlet] - Cleared thread-bound request context: org.acegisecurity.wrapper.SavedRequestAwareWrapper@1b68215
      2007-11-25 21:30:11,875 DEBUG [org.springframework.web.servlet.DispatcherServlet] - Successfully completed request
      2007-11-25 21:30:11,875 DEBUG [org.springframework.web.context.support.XmlWebApplicationContext] - Publishing event in context [[email protected]dafa2c]: ServletRequestHandledEvent: url=[/capcvs/listmytasks.htm]; client=[127.0.0.1]; method=[GET]; servlet=[capcvs]; session=[D82CCF8E25E52647A42238B0A28FA7EB]; user=[admin]; time=[1641ms]; status=[OK]
      2007-11-25 21:30:11,875 DEBUG [org.springframework.web.context.support.XmlWebApplicationContext] - Publishing event in context [[email protected]93c4f1]: ServletRequestHandledEvent: url=[/capcvs/listmytasks.htm]; client=[127.0.0.1]; method=[GET]; servlet=[capcvs]; session=[D82CCF8E25E52647A42238B0A28FA7EB]; user=[admin]; time=[1641ms]; status=[OK]
      I am not sure if there is any blatant error here that i have missed. plz let me know.

      thanks,
      sreedhar.

      Comment


      • #4
        What did your execution() pointcut expression look like? The within() pointcut expression may not be the best choice in this case since the handleRequest() method is actually declared in a base class (AbstractController).

        One possibility might be something like this:

        Code:
        execution(* org.springframework.web.servlet.mvc.AbstractController.handleRequest(..)) && target(com.capcvs.web.controller.task.TaskController)

        Comment


        • #5
          The execution PCD was like
          Code:
          execution(* com.capcvs.web.controller.task.TaskController.handleRequest(..))
          as the TaskController implemented the MultiActionController which in turn extends the Abstractcontroller, I assumed that the above PCD will work.

          the PCD :
          Code:
          execution(* org.springframework.web.servlet.mvc.AbstractController.handleRequest(..)) && target(com.capcvs.web.controller.task.TaskController)
          is giving me this error and am clueless.
          Code:
          org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 201 in XML document from ServletContext resource [/WEB-INF/capcvs-servlet.xml] is invalid; nested exception is org.xml.sax.SAXParseException: The entity name must immediately follow the '&' in the entity reference.
          	at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:369)
          	at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:313)
          	at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:290)
          	at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:142)
          	at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:158)
          	at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:124)
          	at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:92)
          	at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:97)
          	at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:411)
          	at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:338)
          	at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:332)
          	at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:266)
          	at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:236)
          	at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:126)
          	at javax.servlet.GenericServlet.init(GenericServlet.java:211)
          	at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1105)
          	at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:932)
          	at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:3951)
          	at org.apache.catalina.core.StandardContext.start(StandardContext.java:4225)
          	at org.apache.catalina.manager.ManagerServlet.start(ManagerServlet.java:1175)
          	at org.apache.catalina.manager.ManagerServlet.doGet(ManagerServlet.java:368)
          	at javax.servlet.http.HttpServlet.service(HttpServlet.java:689)
          	at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
          	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:252)
          	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
          	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
          	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:178)
          	at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:524)
          	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:126)
          	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:105)
          	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:107)
          	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:148)
          	at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:869)
          	at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:664)
          	at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:527)
          	at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:80)
          	at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:684)
          	at java.lang.Thread.run(Unknown Source)
          Caused by: org.xml.sax.SAXParseException: The entity name must immediately follow the '&' in the entity reference.
          	at org.apache.xerces.parsers.DOMParser.parse(Unknown Source)
          	at org.apache.xerces.jaxp.DocumentBuilderImpl.parse(Unknown Source)
          	at org.springframework.beans.factory.xml.DefaultDocumentLoader.loadDocument(DefaultDocumentLoader.java:78)
          	at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:361)
          	... 37 more
          But if i remove the
          Code:
          && target(com.capcvs.web.controller.task.TaskController
          it works fine.

          Comment


          • #6
            I finally managed to get the stuff working by defining a point cut as below:

            Code:
            package com.capcvs.aop.pointcuts;
            
            import org.aspectj.lang.annotation.Aspect;
            import org.aspectj.lang.annotation.Pointcut;
            
            @Aspect
            public class TestPointcut {
            	@Pointcut("execution(* org.springframework.web.servlet.mvc.AbstractController.handleRequest(..))")
            	public void anyHandleRequest() {}
            	@Pointcut("target(com.capcvs.web.controller.task.TaskController)")
            	public void anyTaskMethod() {}
            	@Pointcut("anyHandleRequest() && anyTaskMethod()")
            	public void anyTaskRequest() {}
            }
            and configuring as below:
            Code:
            	<aop:config>
            		<aop:aspect ref="profiler">
            			<aop:pointcut id="anyTaskMethod"
            				expression="com.capcvs.aop.pointcuts.TestPointcut.anyTaskRequest()"/>
            			<aop:around pointcut-ref="anyTaskMethod"
            			method="profile"/>
            		</aop:aspect>
            	</aop:config>
            But plz let me know if possible, as to why the earlier config was throwing error

            thanks for all the help,
            sreedhar

            Comment


            • #7
              When configuring a pointcut expression in your application context XML file, you can use "and" instead of "&&" to avoid conflicts with special XML characters. For example:

              Code:
              execution(* org.springframework.web.servlet.mvc.AbstractController.handleRequest(..)) and target(com.capcvs.web.controller.task.TaskController)

              Comment


              • #8
                can't find referenced pointcut

                Hi, I just tried examples from chapter 6 of SFW 2.5.
                @Pointcut("execution(* main(..))")
                public void mainMethod() {
                }

                works fine. but

                @AfterReturning("com.dcci.spring.aop.HelloService. testReturnVal()")
                public void anotherTest() {
                System.out.println("OKOK.....");
                }

                Doesn't work. com.dcci.spring.aop.HelloService.testReturnVal()?

                I attach the error message below? Thanks in adavance --Gary

                Does this mean the framework could not find


                Nov 26, 2007 11:46:55 AM org.springframework.context.support.AbstractApplic ationContext prepareRefresh
                INFO: Refreshing org.springframework.context.support.ClassPathXmlAp plicationContext@16672d6: display name [org.springframework.context.support.ClassPathXmlAp plicationContext@16672d6]; startup date [Mon Nov 26 11:46:55 EST 2007]; root of context hierarchy
                Nov 26, 2007 11:46:55 AM org.springframework.beans.factory.xml.XmlBeanDefin itionReader loadBeanDefinitions
                INFO: Loading XML bean definitions from class path resource [com/dcci/spring/aop/application-context.xml]
                Nov 26, 2007 11:46:56 AM org.springframework.context.support.AbstractApplic ationContext obtainFreshBeanFactory
                INFO: Bean factory for application context [org.springframework.context.support.ClassPathXmlAp plicationContext@16672d6]: org.springframework.beans.factory.support.DefaultL istableBeanFactory@c791b9
                Nov 26, 2007 11:46:56 AM org.springframework.beans.factory.support.DefaultL istableBeanFactory preInstantiateSingletons
                INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultL istableBeanFactory@c791b9: defining beans [helloService,org.springframework.aop.config.intern alAutoProxyCreator,helloFromAspectJ]; root of factory hierarchy
                Nov 26, 2007 11:46:56 AM org.springframework.beans.factory.support.DefaultS ingletonBeanRegistry destroySingletons
                INFO: Destroying singletons in org.springframework.beans.factory.support.DefaultL istableBeanFactory@c791b9: defining beans [helloService,org.springframework.aop.config.intern alAutoProxyCreator,helloFromAspectJ]; root of factory hierarchy
                Exception in thread "main" org.springframework.beans.factory.BeanCreationExce ption: Error creating bean with name 'helloService' defined in class path resource [com/dcci/spring/aop/application-context.xml]: Initialization of bean failed; nested exception is java.lang.IllegalArgumentException: error at ::0 can't find referenced pointcut testReturnVal
                at org.springframework.beans.factory.support.Abstract AutowireCapableBeanFactory.doCreateBean(AbstractAu towireCapableBeanFactory.java:547)
                at org.springframework.beans.factory.support.Abstract AutowireCapableBeanFactory$1.run(AbstractAutowireC apableBeanFactory.java:485)
                at java.security.AccessController.doPrivileged(Native Method)
                at org.springframework.beans.factory.support.Abstract AutowireCapableBeanFactory.createBean(AbstractAuto wireCapableBeanFactory.java:455)
                at org.springframework.beans.factory.support.Abstract BeanFactory$1.getObject(AbstractBeanFactory.java:2 51)
                at org.springframework.beans.factory.support.DefaultS ingletonBeanRegistry.getSingleton(DefaultSingleton BeanRegistry.java:169)
                at org.springframework.beans.factory.support.Abstract BeanFactory.getBean(AbstractBeanFactory.java:248)
                at org.springframework.beans.factory.support.Abstract BeanFactory.getBean(AbstractBeanFactory.java:170)
                at org.springframework.beans.factory.support.DefaultL istableBeanFactory.preInstantiateSingletons(Defaul tListableBeanFactory.java:413)
                at org.springframework.context.support.AbstractApplic ationContext.finishBeanFactoryInitialization(Abstr actApplicationContext.java:735)
                at org.springframework.context.support.AbstractApplic ationContext.refresh(AbstractApplicationContext.ja va:369)
                at org.springframework.context.support.ClassPathXmlAp plicationContext.<init>(ClassPathXmlApplicationCon text.java:122)
                at org.springframework.context.support.ClassPathXmlAp plicationContext.<init>(ClassPathXmlApplicationCon text.java:66)
                at com.dcci.spring.aop.SpringBoot.main(SpringBoot.jav a:9)
                Caused by: java.lang.IllegalArgumentException: error at ::0 can't find referenced pointcut testReturnVal
                at org.aspectj.weaver.tools.PointcutParser.parsePoint cutExpression(PointcutParser.java:315)
                at org.springframework.aop.aspectj.AspectJExpressionP ointcut.buildPointcutExpression(AspectJExpressionP ointcut.java:197)
                at org.springframework.aop.aspectj.AspectJExpressionP ointcut.checkReadyToMatch(AspectJExpressionPointcu t.java:184)
                at org.springframework.aop.aspectj.AspectJExpressionP ointcut.getClassFilter(AspectJExpressionPointcut.j ava:165)
                at org.springframework.aop.support.AopUtils.canApply( AopUtils.java:189)
                at org.springframework.aop.support.AopUtils.canApply( AopUtils.java:244)
                at org.springframework.aop.support.AopUtils.findAdvis orsThatCanApply(AopUtils.java:278)
                at org.springframework.aop.framework.autoproxy.Abstra ctAdvisorAutoProxyCreator.findAdvisorsThatCanApply (AbstractAdvisorAutoProxyCreator.java:113)
                at org.springframework.aop.framework.autoproxy.Abstra ctAdvisorAutoProxyCreator.findEligibleAdvisors(Abs tractAdvisorAutoProxyCreator.java:85)
                at org.springframework.aop.framework.autoproxy.Abstra ctAdvisorAutoProxyCreator.getAdvicesAndAdvisorsFor Bean(AbstractAdvisorAutoProxyCreator.java:66)
                at org.springframework.aop.framework.autoproxy.Abstra ctAutoProxyCreator.postProcessAfterInitialization( AbstractAutoProxyCreator.java:296)
                at org.springframework.beans.factory.support.Abstract AutowireCapableBeanFactory.applyBeanPostProcessors AfterInitialization(AbstractAutowireCapableBeanFac tory.java:334)
                at org.springframework.beans.factory.support.Abstract AutowireCapableBeanFactory.initializeBean(Abstract AutowireCapableBeanFactory.java:1368)
                at org.springframework.beans.factory.support.Abstract AutowireCapableBeanFactory.doCreateBean(AbstractAu towireCapableBeanFactory.java:540)
                ... 13 more


                package com.dcci.spring.aop;

                public class HelloService {

                public void main() {
                System.out.println("Hello World!");
                }

                public void greeting(String name){
                System.out.println("Hi, " + name);
                }

                public int testReturnVal(){
                int returnVal=5;
                System.out.println("i=" + returnVal);
                return returnVal;
                }

                }


                @AfterReturning("com.dcci.spring.aop.HelloService. testReturnVal()")
                public void anotherTest() {
                System.out.println("OKOK.....");
                }

                Comment


                • #9
                  Problem resolved :: AOP - @AspectJ

                  Not sure this is a bug or not. But after I change the code to the following form, it works.

                  @Pointcut("execution(* testReturnVal(..))")
                  public void anotherMethod() {
                  }

                  @AfterReturning(pointcut="anotherMethod()", returning="retVal")
                  public void doAccessCheck(Object retVal) {
                  System.out.println("retVal=" + retVal);
                  System.out.println("Another......");
                  }



                  Originally posted by [email protected] View Post
                  Hi, I just tried examples from chapter 6 of SFW 2.5.
                  @Pointcut("execution(* main(..))")
                  public void mainMethod() {
                  }

                  works fine. but

                  @AfterReturning("com.dcci.spring.aop.HelloService. testReturnVal()")
                  public void anotherTest() {
                  System.out.println("OKOK.....");
                  }

                  Doesn't work. com.dcci.spring.aop.HelloService.testReturnVal()?

                  I attach the error message below? Thanks in adavance --Gary

                  Does this mean the framework could not find


                  Nov 26, 2007 11:46:55 AM org.springframework.context.support.AbstractApplic ationContext prepareRefresh
                  INFO: Refreshing org.springframework.context.support.ClassPathXmlAp plicationContext@16672d6: display name [org.springframework.context.support.ClassPathXmlAp plicationContext@16672d6]; startup date [Mon Nov 26 11:46:55 EST 2007]; root of context hierarchy
                  Nov 26, 2007 11:46:55 AM org.springframework.beans.factory.xml.XmlBeanDefin itionReader loadBeanDefinitions
                  INFO: Loading XML bean definitions from class path resource [com/dcci/spring/aop/application-context.xml]
                  Nov 26, 2007 11:46:56 AM org.springframework.context.support.AbstractApplic ationContext obtainFreshBeanFactory
                  INFO: Bean factory for application context [org.springframework.context.support.ClassPathXmlAp plicationContext@16672d6]: org.springframework.beans.factory.support.DefaultL istableBeanFactory@c791b9
                  Nov 26, 2007 11:46:56 AM org.springframework.beans.factory.support.DefaultL istableBeanFactory preInstantiateSingletons
                  INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultL istableBeanFactory@c791b9: defining beans [helloService,org.springframework.aop.config.intern alAutoProxyCreator,helloFromAspectJ]; root of factory hierarchy
                  Nov 26, 2007 11:46:56 AM org.springframework.beans.factory.support.DefaultS ingletonBeanRegistry destroySingletons
                  INFO: Destroying singletons in org.springframework.beans.factory.support.DefaultL istableBeanFactory@c791b9: defining beans [helloService,org.springframework.aop.config.intern alAutoProxyCreator,helloFromAspectJ]; root of factory hierarchy
                  Exception in thread "main" org.springframework.beans.factory.BeanCreationExce ption: Error creating bean with name 'helloService' defined in class path resource [com/dcci/spring/aop/application-context.xml]: Initialization of bean failed; nested exception is java.lang.IllegalArgumentException: error at ::0 can't find referenced pointcut testReturnVal
                  at org.springframework.beans.factory.support.Abstract AutowireCapableBeanFactory.doCreateBean(AbstractAu towireCapableBeanFactory.java:547)
                  at org.springframework.beans.factory.support.Abstract AutowireCapableBeanFactory$1.run(AbstractAutowireC apableBeanFactory.java:485)
                  at java.security.AccessController.doPrivileged(Native Method)
                  at org.springframework.beans.factory.support.Abstract AutowireCapableBeanFactory.createBean(AbstractAuto wireCapableBeanFactory.java:455)
                  at org.springframework.beans.factory.support.Abstract BeanFactory$1.getObject(AbstractBeanFactory.java:2 51)
                  at org.springframework.beans.factory.support.DefaultS ingletonBeanRegistry.getSingleton(DefaultSingleton BeanRegistry.java:169)
                  at org.springframework.beans.factory.support.Abstract BeanFactory.getBean(AbstractBeanFactory.java:248)
                  at org.springframework.beans.factory.support.Abstract BeanFactory.getBean(AbstractBeanFactory.java:170)
                  at org.springframework.beans.factory.support.DefaultL istableBeanFactory.preInstantiateSingletons(Defaul tListableBeanFactory.java:413)
                  at org.springframework.context.support.AbstractApplic ationContext.finishBeanFactoryInitialization(Abstr actApplicationContext.java:735)
                  at org.springframework.context.support.AbstractApplic ationContext.refresh(AbstractApplicationContext.ja va:369)
                  at org.springframework.context.support.ClassPathXmlAp plicationContext.<init>(ClassPathXmlApplicationCon text.java:122)
                  at org.springframework.context.support.ClassPathXmlAp plicationContext.<init>(ClassPathXmlApplicationCon text.java:66)
                  at com.dcci.spring.aop.SpringBoot.main(SpringBoot.jav a:9)
                  Caused by: java.lang.IllegalArgumentException: error at ::0 can't find referenced pointcut testReturnVal
                  at org.aspectj.weaver.tools.PointcutParser.parsePoint cutExpression(PointcutParser.java:315)
                  at org.springframework.aop.aspectj.AspectJExpressionP ointcut.buildPointcutExpression(AspectJExpressionP ointcut.java:197)
                  at org.springframework.aop.aspectj.AspectJExpressionP ointcut.checkReadyToMatch(AspectJExpressionPointcu t.java:184)
                  at org.springframework.aop.aspectj.AspectJExpressionP ointcut.getClassFilter(AspectJExpressionPointcut.j ava:165)
                  at org.springframework.aop.support.AopUtils.canApply( AopUtils.java:189)
                  at org.springframework.aop.support.AopUtils.canApply( AopUtils.java:244)
                  at org.springframework.aop.support.AopUtils.findAdvis orsThatCanApply(AopUtils.java:278)
                  at org.springframework.aop.framework.autoproxy.Abstra ctAdvisorAutoProxyCreator.findAdvisorsThatCanApply (AbstractAdvisorAutoProxyCreator.java:113)
                  at org.springframework.aop.framework.autoproxy.Abstra ctAdvisorAutoProxyCreator.findEligibleAdvisors(Abs tractAdvisorAutoProxyCreator.java:85)
                  at org.springframework.aop.framework.autoproxy.Abstra ctAdvisorAutoProxyCreator.getAdvicesAndAdvisorsFor Bean(AbstractAdvisorAutoProxyCreator.java:66)
                  at org.springframework.aop.framework.autoproxy.Abstra ctAutoProxyCreator.postProcessAfterInitialization( AbstractAutoProxyCreator.java:296)
                  at org.springframework.beans.factory.support.Abstract AutowireCapableBeanFactory.applyBeanPostProcessors AfterInitialization(AbstractAutowireCapableBeanFac tory.java:334)
                  at org.springframework.beans.factory.support.Abstract AutowireCapableBeanFactory.initializeBean(Abstract AutowireCapableBeanFactory.java:1368)
                  at org.springframework.beans.factory.support.Abstract AutowireCapableBeanFactory.doCreateBean(AbstractAu towireCapableBeanFactory.java:540)
                  ... 13 more


                  package com.dcci.spring.aop;

                  public class HelloService {

                  public void main() {
                  System.out.println("Hello World!");
                  }

                  public void greeting(String name){
                  System.out.println("Hi, " + name);
                  }

                  public int testReturnVal(){
                  int returnVal=5;
                  System.out.println("i=" + returnVal);
                  return returnVal;
                  }

                  }


                  @AfterReturning("com.dcci.spring.aop.HelloService. testReturnVal()")
                  public void anotherTest() {
                  System.out.println("OKOK.....");
                  }

                  Comment


                  • #10
                    Gary -

                    The original pointcut expression you supplied:

                    Code:
                    com.dcci.spring.aop.HelloService.testReturnVal()
                    will attempt to reference a named pointcut (defined with @Pointcut) called testReturnVal. However, it looks like you were trying to create a pointcut expression to match calls to an existing testReturnVal method. When creating a pointcut expression, you need to use one of the supported pointcut designators, such as execution(); otherwise, a simple method signature will be interpreted as a named pointcut. See here for more details on the available pointcut designators:

                    http://static.springframework.org/sp...ts-designators

                    Comment


                    • #11
                      Thanks Mike.
                      It makes sense now. I have post my fix yesterday.
                      --Gary

                      Originally posted by Mike Bingham View Post
                      Gary -

                      The original pointcut expression you supplied:

                      Code:
                      com.dcci.spring.aop.HelloService.testReturnVal()
                      will attempt to reference a named pointcut (defined with @Pointcut) called testReturnVal. However, it looks like you were trying to create a pointcut expression to match calls to an existing testReturnVal method. When creating a pointcut expression, you need to use one of the supported pointcut designators, such as execution(); otherwise, a simple method signature will be interpreted as a named pointcut. See here for more details on the available pointcut designators:

                      http://static.springframework.org/sp...ts-designators

                      Comment


                      • #12
                        Just to fix the broken link:
                        http://static.springframework.org/sp...ng-aop-proxies
                        Because the "current" isn't working.

                        By the way, Mike, do you mean that there is no pointcut capable of advising all called/executed internal methods?
                        I've been trying to log all methods that are called in my controller that extends SimpleFormController. And by that I mean calling all inherited methods, including the finalones. Is that possible?

                        Comment


                        • #13
                          Not with basic Spring AOP. You will need a fullblown AOP solution, like AspectJ, for that in combination with loadtime or compile time weaving.

                          Comment

                          Working...
                          X