Spring AOPのAspectJ
8602 ワード
SpringでAspectJを用いてAOPを実現するには2つの方法がある.
ここでは、AspectJの式execution(修飾子?戻り型宣言タイプ?メソッド名(パラメータタイプ)異常タイプ?)が任意のpublicメソッドexecution(public*(*(.))を実行し、setで始まるメソッドexecution(*set*(.))が少なくとも1つのパラメータを実行し、最初のパラメータがStringタイプのメソッドexecution(**(java.lang.String....))サービスクラスのメソッドexecution(*com.chm.test.Services.*(.))を実行するcom.chm.testパッケージおよびそのサブパッケージのメソッドexecution(*com.chm.test.*)を実行します.
二.Springプロファイルでの構成
@Aspect
public class MyAspectJ
{
@Pointcut("execution(public * eat(..)) && target(com.chm.test.Person)")
public void pointcut()
{
}
@Before("pointcut()")
public void beforeMethod(JoinPoint joinPoint)
{
System.out.println(" ");
}
@Around("pointcut()")
public void aroundMehtod(ProceedingJoinPoint joinPoint)
{
System.out.println("before");
try
{
joinPoint.proceed();
}
catch (Throwable e)
{
e.printStackTrace();
}
System.out.println("after");
}
@After("pointcut()")
public void afterMethod(JoinPoint point)
{
System.out.println(" ");
}
}
<bean id="person" class="com.chm.test.Person">
<property name="name" value="charming"></property>
</bean>
<bean class="org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator"></bean> <!-- -->
<bean id="myaspectj" class="com.chm.test.MyAspectJ"></bean>
ここでは、AspectJの式execution(修飾子?戻り型宣言タイプ?メソッド名(パラメータタイプ)異常タイプ?)が任意のpublicメソッドexecution(public*(*(.))を実行し、setで始まるメソッドexecution(*set*(.))が少なくとも1つのパラメータを実行し、最初のパラメータがStringタイプのメソッドexecution(**(java.lang.String....))サービスクラスのメソッドexecution(*com.chm.test.Services.*(.))を実行するcom.chm.testパッケージおよびそのサブパッケージのメソッドexecution(*com.chm.test.*)を実行します.
二.Springプロファイルでの構成
public class MyAspectJ
{
public void beforeMethod(JoinPoint joinPoint)
{
System.out.println(" ");
}
public void aroundMehtod(ProceedingJoinPoint joinPoint)
{
System.out.println("before");
try
{
joinPoint.proceed();
}
catch (Throwable e)
{
e.printStackTrace();
}
System.out.println("after");
}
public void afterMethod(JoinPoint point)
{
System.out.println(" ");
}
}
<?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-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> <bean id="person" class="com.chm.test.Person"> <property name="name" value="charming"></property> </bean> <bean id="myAspectJ" class="com.chm.test.MyAspectJ"></bean> <aop:config> <aop:aspect ref="myAspectJ"> <aop:pointcut expression="execution(public * *(..))" id="pointcut"/> <aop:before method="beforeMethod" pointcut="execution(public * eat(..))"/> <aop:around method="aroundMehtod" pointcut-ref="pointcut"/> <aop:after method="afterMethod" pointcut-ref="pointcut"/> </aop:aspect> </aop:config> </beans>