Ответ 1
Spring позволяет нам легко использовать AOP. Вот простой пример регистрации:
@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...");
}
}
Затем просто настройте свой applicationContext.xml(или эквивалент):
<aop:aspectj-autoproxy>
<aop:include name="myLogger"/>
</aop:aspectj-autoproxy>
<bean id="myLogger" class="com.example.aspect.MyLogger"/>
В классе MyLogger вы заметите, что я указал @After
прямо над методом. Это называется советом, и в основном это указывает, что этот метод "журнала" будет называться после рассматриваемого метода. Другие варианты включают @Before, @Around, @AfterThrowing
.
Выражение "execution(* com.example.web.HomeController.*(..))"
называется выражением pointcut и указывает, на что мы нацеливаемся (в данном случае все методы класса HomeController).
P.S. Пространство имен aop
(xmlns:aop="http://www.springframework.org/schema/aop"
) и расположение схемы (зависит от версии) должны быть добавлены в ваш applicationContext.xml справа вверху. Вот моя настройка:
<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">