Newsletter

Example On Spring AOP Before Advice, After Advice

Spring » on Jul 25, 2012 { 24 Comments } By Sivateja

Hi friends…, will see one example on spring Before Advice, and After Advice.

Files Required

  • MyAfterAdvice.java
  • MyImplClass.java
  • MyInterFace.java
  • MyWelcomeAdvice.java
  • OurLogic.java
  • spconfig.xml

Directory Structure

MyAfterAdvice.java

package java4s;

import java.lang.reflect.Method;
import org.springframework.aop.AfterReturningAdvice;

public class MyAfterAdvice implements AfterReturningAdvice
{

    public void afterReturning(Object returnValue, Method m,Object args[],Object target)throws Exception
    {
        System.out.println("Am from AfterAdvice to "+m.getName());
    }

}

MyImplClass.java

package java4s;

public class MyImplClass implements MyInterFace
{
    public void m1(){
        System.out.println("This is from m1 method");
    }

    public void m2(){
        System.out.println("This is from m2 method");
    }
}

MyInterFace.java

package java4s;

public interface MyInterFace
{
    void m1();
    void m2();
}

MyWelcomeAdvice.java

package java4s;

import java.lang.reflect.Method;
import org.springframework.aop.MethodBeforeAdvice;

public class MyWelcomeAdvice implements MethodBeforeAdvice
{

    public void before(Method m, Object args[], Object target)throws Exception
    {
        System.out.println("Am from BeforeAdvice to "+m.getName());
    }

}

OurLogic.java

package java4s;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

public class OurLogic
{
    public static void main(String args[])
    {
        Resource res = new ClassPathResource("spconfig.xml");
        BeanFactory factory = new XmlBeanFactory(res);

        MyInterFace inter =(MyInterFace)factory.getBean("id4");
        inter.m1();
        inter.m2();
    }
}

spconfig.xml

<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
            "http://www.springframework.org/dtd/spring-beans-2.0.dtd">

<beans>

 <bean id="id1" class="java4s.MyImplClass" />
 <bean id="id2" class="java4s.MyWelcomeAdvice" />
 <bean id="id3" class="java4s.MyAfterAdvice" />
 <bean id="id4" class="org.springframework.aop.framework.ProxyFactoryBean">

      <property name="proxyInterfaces" value="java4s.MyInterFace" />
      <property name="interceptorNames" >
                  <list>
                       <value>id2</value>
                       <value>id3</value>
                   </list>
       </property>
       <property name="target">
               <ref bean="id1"/>       
       </property>     

 </bean>

</beans>

Output:

Explanation:

Actually in spring frame work, while creating a spring bean we need to follow POJIPOJO model.  It means a spring bean is a combination of an interface and implementation class. In AOP always we need to create a spring bean in the form of interface and implementation class only, because the IOC container internally creates proxy class by implementing that interface with the help of ProxyFactoryBean.

In spring configuration file, we need to configure a predefined bean class called ProxyFactoryBean, this class is used to configure our bean class and its required advices as a group.

In the client application, we are passing id of ProxyFactoryBean (id4) to get the object, because we need proxyed object, but not target one hope you understand.  In client application we cannot typecast the object into our bean class type, because internally the object is created for proxy class but not for our bean class right 🙂  so we need to typecast into interface type because the proxy class will also implements the same interface internally remember…!!

In OurLogic.java if we typecast into our class type, then it will generates ClassCastException exception.

Hope you are clear, if not refer previous concepts of AOP.

 

 

​​

You Might Also Like

  ::. About the Author .::

Java4s_Author
Sivateja Kandula - Java/J2EE Full Stack Developer
Founder of Java4s - Get It Yourself, A popular Java/J2EE Programming Blog, Love Java and UI frameworks.
You can sign-up for the Email Newsletter for your daily dose of Java tutorials.

Comments

24 Responses to “Example On Spring AOP Before Advice, After Advice”
  1. Abhishek says:

    Hi,

    Thanks for this post. But i have confusion in OurLogic.java,line no.15, it should be MyImplClass inter =(MyImplClass)factory.getBean(“id4”); rather we have used MyInterFace inter(MyInterFace)factory.getBean(“id4”); because MyInterFace is an interface and we can;t instansiate interface. Hope you got my problem.please help

  2. Java4s says:

    @Abhishek

    We are not creating any object to that interface, we just taking object into interface reference, like how we are using List and ArrayList 🙂

    Hope you are clear.

  3. Arin says:

    Thanks a lot for providing such a wonderfull tutorial with easy to understand words….I would request you to write books. It will a block buster…Trust me.

  4. abhimanyu says:

    i love the way u given the explanantion..about each and every file…thanks a lot for these……….

  5. Harika says:

    Hi sir….
    For spring Aop….what jar files is required…When i was implementing the above program..I am getting error like The hierarchy of the type is inconsitent….plz help me on this….I have added sprinaop.jar…plz reply me fast sir…:)

  6. Rajak says:

    Hi Sir,

    Thank you for providing such a useful tutorial in a easy understanding way.
    I got below error when executing the above program. Please have a look into it and fix it asap.

    Error creating bean with name ‘id4’ defined in class path resource [BA_Adviceconfig.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.springframework.aop.framework.ProxyFactoryBean]: Constructor threw exception; nested exception is java.lang.NoClassDefFoundError: org/aopalliance/intercept/MethodInterceptor

  7. Priya says:

    Hi sir,

    When I tried this example in my laptop am facing the error like this
    “hierarchy of the type is inconsitent”
    PLz help me to resolve this error. even though i addded the jarnamely spring-aop-3.0.2.RELEASE.jar.

    PLZ explain me any other steps need to be followed

  8. Prakash says:

    I am also the facing the same error Priya faces could you please help.I have imported spring aop jar.Even then facing the same issue.

  9. Prakash says:

    Try adding aopalliance.jar as the Advice method is defined in this jar

  10. Swamy Nadhan G says:

    U have great technique of teaching dude….Please put some more technologies in u r menu….

  11. Shubha says:

    Hi Sir, Your way of explaination is very neat and understandable. But I am getting this error while compiling.
    Error:”The hierarchy of the class is inconsistent”. This error is shown for both ‘before’ and ‘after’ class. Please help me in resolving this issue.
    Thanks in advance.

  12. babu says:

    @Shubha

    hi,

    http://sourceforge.net/projects/aopalliance/files/aopalliance/1.0/

    Download the above jar and put it in your buildpath

  13. gulab says:

    In “spconfig.xml” Line No : 15 ()

    Why we use this when we implemented in the “id1”.

    Please explain.

  14. Hi,
    Thanks a lot for this Tutorial.
    In above example we face an Exception from configuration file. We are sending a list of values injected to property ‘interceptorNames’ to the predefined Spring bean ProxyFactoryBean.
    The Exception is:
    The content of element type “list” must match “(bean|ref|idref|value|null|list|set|map|props)*”.

    Please explain to me.
    Thank in Advance.
    Appu

  15. Manikandan says:

    Hi all,

    For avoid error you have to set the build path for the following jar files,
    1. spring-core
    2. spring-beans
    3. spring-aop
    4. commons-logging and
    5. aopalliance.

    The final one removes the “The hierarchy of the class is inconsistent” issues.

    I hope you will get clear.

    Thanks friends!!!

  16. Ashok says:

    If U provide real time use cases …we can understand easily and ur site get more popular as………plss provide use cases also..@@

  17. yellappa says:

    thaq sir

  18. Guru says:

    Hi siva , getting the below error while trying with above example . please provide solution for this ASAP .
    Exception in thread “main” org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘id4’: FactoryBean threw exception on object creation; nested exception is org.springframework.aop.framework.AopConfigException: Unknown advisor type class advice1.MyImplClass; Can only include Advisor or Advice type beans in interceptorNames chain except for last entry,which may also be target or TargetSource; nested exception is org.springframework.aop.framework.adapter.UnknownAdviceTypeException: Advice object [advice1.MyImplClass@ec99b58] is neither a supported subinterface of [org.aopalliance.aop.Advice] nor an [org.springframework.aop.Advisor]

  19. Chandu says:

    U r really inspirable ,……

  20. Atul Srivastava says:

    There can not be as simplest way as you have used here. Great!!!

  21. Atul Srivastava says:

    Great Job.

  22. Sripriya says:

    Hey,

    Can you please explain me this example step by step i.e., in more detailed form. I am little confused.

  23. chandu says:

    Can u plz provide Junit Tutorial

  24. kishori says:

    If I am having more than one interface then, do I need to typecast with that interface by using below line
    MyInterFace inter =(MyInterFace)factory.getBean("id4");

    e.g. MyInterface1 inter1 = (MyInterface1)factory.getBean("id4");

Name*
Mail*
Website



By posting your answer, you agree to our comments policy.
Most Recent Posts from Top Categories
Spring Boot Hibernate Spring
Contact | About Us | Privacy Policy | Advertise With Us

© 2010 - 2024 Java4s - Get It Yourself.
The content is copyrighted to Sivateja Kandula and may not be reproduced on other websites.