logging with AOP in spring?

ぃ、小莉子 提交于 2019-11-27 18:02:28

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">
Avinash Singh

You need to perform several steps to integrate Aspectj,

  1. Install AspectJ , http://www.cs.utep.edu/cheon/cs3360/project/proj1/installing-aspectj.txt
  2. Add your aop.xml to META-INF\aop.xml in your project
  3. Add aspectjrt-x.x.0.jar and aspectjweaver-x.x.0.jar in your project classpath
  4. Add -javaagent:/path to aspectj installation/aspectjweaver-1.7.0.jar to your server's JVM .

Here is a sample aop.xml,

<aspectj>
 <aspects>
  <aspect name="test.MySimpleLoggerAspect" />
 </aspects>
 <weaver>
  <include within="test.myproject.*" />
 </weaver>     
</aspectj>

if you are already using spring then it is better to use Spring to simplify your setup, here is a good example , http://forum.springsource.org/showthread.php?61551-Bean-Factory-is-not-set-for-BeanConfigurerSupport

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!