Pointcut не работает с Spring AOP

Чтобы реализовать ведение журнала с помощью Spring AOP, я выполнил следующие простые шаги. Но похоже, что он не работает. Любая помощь будет полезна

1) Создан класс MyLoggingAspect.

    import org.aspectj.lang.ProceedingJoinPoint;

public class MyLoggingAspect
{

    public MyLoggingAspect() {
        super();
        System.out.println("Instantiated MyLoggingAspect");     
    }

    public Object log(ProceedingJoinPoint call) throws Throwable
    {
        System.out.println("from logging aspect: entering method [" + call.toShortString()
                            +"] with param:"+call.getArgs()[0] );

        Object point =  call.proceed();

        System.out.println("from logging aspect: exiting method [" + call.toShortString()   
                            + "with return as:" +point);        

        return point;
    }

}

2) Создал класс (TixServiceImpl), в котором я хочу вести журнал

public class TixServiceImpl implements TixService{

    @Override
    public void calculateSomething() {
        String s = "did some calculation..";
        System.out.println(s);
    }

    @Override
    public String getTixName() {
        return null;
    }
}

3) Создал файл spring-aspectj.xml.

<beans...    
    <bean id="LoggingAspect"  class = "MyLoggingAspect"/>
    <aop:config>
          <aop:aspect ref="LoggingAspect">
             <aop:pointcut id="myCutLogging"
                    expression="execution(* TixService*.*(..))"/>
             <aop:around pointcut-ref="myCutLogging" method="log"/>
          </aop:aspect>
    </aop:config>    
</beans>

4) Создан простой тестовый клиент (TixClient)

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

public class TixClient {

    public static void main(String[] a){

        ApplicationContext context = new FileSystemXmlApplicationContext("conf/spring-aspectj.xml");

        TixService tix = new TixServiceImpl();
        tix.calculateSomething();
        String s = tix.getTixName();

        System.out.println("End of the the client invocation!!"); 
    }   
}

5) Это дает мне следующий Вывод

...
Instantiated MyLoggingAspect
did some calculation..
End of the the client invocation!!

person a-sak    schedule 18.01.2009    source источник


Ответы (2)


Я просто проверяю ваш код, но у меня есть подозрение, что проблема в том, что вы не получаете свой экземпляр TixServiceImpl из Spring, а создаете его вручную в своем TixClient. Я думаю, что ваш TixService должен быть bean-компонентом Spring, полученным из Spring ApplicationContext, чтобы у Spring была возможность настроить аспекты в возвращаемом экземпляре.

person Scott Bale    schedule 18.01.2009
comment
Спасибо за подсказку, сработало. Было бы хорошо, если бы это было упомянуто в образцах/примерах/учебниках, доступных в Интернете. - person a-sak; 19.01.2009

Скотт Бэйл прав: пусть Spring создаст для вас TixServiceImpl. Также в подобных случаях может помочь включение ведения журнала Springs, поскольку оно сообщает вам, сколько целей для аспекта/avice было найдено.

person tobsen    schedule 18.01.2009
comment
Как включить весеннее ведение журнала? - person Grant Cermak; 30.12.2010
comment
В документации Spring представлены различные способы включения ведения журнала: static.springsource.org/spring/docs/3.0.x/ - person tobsen; 01.01.2011