AOP(Spring)
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:context="http://www.springframework.org/schema/context"
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/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
<context:annotation-config/>
<context:component-scan base-package="com.test"/>
<bean id="logInterceptor" class="com.test.aop.LogInterceptor"></bean>
<aop:config>
<aop:pointcut id="myMethod"
expression="execution(public * com.test.service..*.*(..))" />
<aop:aspect id="logAspect" ref="logInterceptor">
<aop:before method="before" pointcut-ref="myMethod"/>
<aop:after-returning method="afterReturning" pointcut-ref="myMethod"/>
</aop:aspect>
</aop:config>
</beans>
アノテーション式(Spring 2.5から)
メリット:見やすい。
<?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:context="http://www.springframework.org/schema/context"
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/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
<context:annotation-config/>
<context:component-scan base-package="com.test"/>
<aop:aspectj-autoproxy/>
</beans>
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class LogInterceptor {
@Pointcut("execution(public * com.test.dao..*.*(..))")
public void myMethod(){}
@Before(value="myMethod()")
public void before(){
//do something
}
@AfterReturning("myMethod()")
public void afterReturning(){
//do something
}
@Around(value="myMethod()")
public void around(ProceedingJoinPoint pjp) throws Throwable{
//do something
pjp.proceed();
//do something
}
}