logging with AOP in spring?

aspectj, java, log4j, spring, spring-mvc

Solution

Spring makes it really easy for us to make use of AOP. Here's a simple logging example:

@Aspect
public class MyLogger {

    private Logger log = Logger.getLogger(getClass());

    @After("execution(* com.example.web.HomeController.*(..))")
    public void log(JoinPoint point) {
        log.info(point.getSignature().getName() + " called...");
    }
}

Then simply configure your applicationContext.xml (or equivalent):

    <aop:aspectj-autoproxy>
        <aop:include name="myLogger"/>
    </aop:aspectj-autoproxy>

    <bean id="myLogger" class="com.example.aspect.MyLogger"/>

You'll notice in the MyLogger class that I specified `@After` right above the method. This is called the advice and it basically specifies that this 'log' method will be called after the method in question. Other options include `@Before, @Around, @AfterThrowing`.

The expression `"execution(* com.example.web.HomeController.*(..))"` is called a pointcut expression and specifies what we're targeting (in this case all methods of the HomeController class).

P.S. The `aop` namespace (`xmlns:aop="http://www.springframework.org/schema/aop"`) and the schema location (version dependent) would need to be added to your applicationContext.xml right at the top. Here is my setup:

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">

Problem

I am new to spring in my office . So there is no guidance for me. I need to implement the logging with the `AOP` using the `log4j`. I have implemented the logging without `AOP` in basic `spring MVC` example ? Also did the small sample in `AOP` using the `aspectJ` without logging (just made the `Sysout`) ? I don't know how to integrate it ? Can any one please give me a start up idea? Good answers are definitely appreciated ...

Original source

Related problems