Spring学習ノート14---AspectJ前置通知後置通知
2936 ワード
package aspectj;
public interface ICal {
int add(int i, int j);
int sub(int i, int j);
}
package aspectj;
import org.springframework.stereotype.Component;
@Component
public class CalImpl implements ICal {
@Override
public int add(int i, int j) {
return i + j;
}
@Override
public int sub(int i, int j) {
return i - j;
}
}
package aspectj;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.omg.CORBA.Object;
import org.springframework.stereotype.Component;
import java.util.Arrays;
import java.util.List;
// , IOC
@Aspect
@Component
public class Logging {
// ,target
@Before("execution(public int aspectj.CalImpl.add(int, int))")
public void beforeMethod(JoinPoint joinPoint) {
String name = joinPoint.getSignature().getName();
List args = Arrays.asList(joinPoint.getArgs());
System.out.println("before Method name : " + name + " args : " + args);
}
// ,,target ,
// ,
@After("execution(public int aspectj.CalImpl.add(int,int))")
public void afterMethod(JoinPoint joinPoint) {
String name = joinPoint.getSignature().getName();
List args = Arrays.asList(joinPoint.getArgs());
System.out.println("after Method name : " + name + " args end");
}
}
package aspectj;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("aspectj//application.xml");
ICal iCal = ctx.getBean(ICal.class);
int result = iCal.add(1, 1);
System.out.println("result : " + result);
}
}
<?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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<context:component-scan base-package="aspectj"></context:component-scan>
<!-- aspectj -->
<aop:aspectj-autoproxy/>
</beans>