Wednesday, March 11, 2009

Logging with Spring AOP

The bean to intercept:

package com.pierre.aop;

public class ExampleBeanClass implements IExampleBeanClass {
public String getMessage() {
return "ciao";
}
}



and its interface:

package com.pierre.aop;

public interface IExampleBeanClass {
String getMessage();
}


The interceptor:

package com.pierre.aop;

import org.aspectj.lang.JoinPoint;

/**
 * Aspect class for the Spring/AspectJ Logging example shown in the blog
 * 
 * @author vernetto
 */
public class LoggingAspect
{
/**
* Log method entry.
* @param joinPoint
*/
public void logEntry(final JoinPoint joinPoint)
{
log("Entering method " + joinPoint.getSignature().getName() + "...");
}

/**
* Log method exit.
* @param joinPoint
*/
public void logExit(final JoinPoint joinPoint)
{
log("Exiting method " + joinPoint.getSignature().getName() + ".");
}

/**
* Log method exit after returning.
* @param joinPoint
*/
public void logExitAfterReturn(final JoinPoint joinPoint)
{
log( "Exiting method (after return) "
+ joinPoint.getSignature().getName() + ".");
}

/**
* "Log" the provided String.
* @param messageToLog String to be logged.
*/
public static void log(final String messageToLog)
{
System.err.println(messageToLog);
}
}



the Main:

package com.pierre.aop;

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {
public static void main(String[] args) {
final ConfigurableApplicationContext context =
new ClassPathXmlApplicationContext("spring-aop-logging-context.xml");
final IExampleBeanClass example =
(IExampleBeanClass) context.getBean("exampleBean");
System.out.println(example.getMessage());
context.close();
}
}



and, at last, the XML:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">

<!-- Normal Spring-exposed bean. -->
<bean id="exampleBean" class="com.pierre.aop.ExampleBeanClass">
</bean>
<!-- The Aspect itself. -->
<bean id="exampleLoggingAspect" class="com.pierre.aop.LoggingAspect" />

<aop:config>
<!-- The Pointcut(s). -->
<aop:pointcut id="loggingPointcut" expression="within(com.pierre.aop.ExampleBeanClass)" />
<!-- The Advice(s). -->
<aop:aspect id="loggingAspect" ref="exampleLoggingAspect">
<aop:before pointcut-ref="loggingPointcut" method="logEntry" />
<aop:after pointcut-ref="loggingPointcut" method="logExit" />
<aop:after-returning pointcut-ref="loggingPointcut" method="logExitAfterReturn" />
</aop:aspect>

</aop:config>

</beans>


No comments: