Spring AOPブロック指定方法
5197 ワード
Spring AOPでは、3つの一般的な概念があります.Advice、Pointcut、Advisorは、次のように説明します.
Advies:一つのmethodが実行される前または実行後の動作を表します.
Pointcut:methodの名前または正規表現によって一つのmethodをブロックすることを表します.
Advisor:AdviceとPointcutからなる独立したユニットで、proxy factoryオブジェクトに送ることができます.
Advies:一つのmethodが実行される前または実行後の動作を表します.
Pointcut:methodの名前または正規表現によって一つのmethodをブロックすることを表します.
Advisor:AdviceとPointcutからなる独立したユニットで、proxy factoryオブジェクトに送ることができます.
package testaop;
public class CustomerService {
private String name;
private String url;
public void printName(){
System.out.println("Customer name "+ name);
}
public void printURL() {
System.out.println("Customer website : " + this.url);
}
public void printThrowException() {
throw new IllegalArgumentException();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
次に、MethodInterceptorを実現したクラスを作成するには、「methodInvocations.proceed」を呼び出す必要があります. 元の方法で実行し続けると、元の方法は実行されません.package testaop;
import java.util.Arrays;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
public class CustomerInterceptor implements MethodInterceptor {
@Override
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
System.out.println("Method name : "
+ methodInvocation.getMethod().getName());
System.out.println("Method arguments : "
+ Arrays.toString(methodInvocation.getArguments()));
// same with MethodBeforeAdvice MethodBeforeAdvice
System.out.println("CustomerService: Before method CustomerService!");
try {
// proceed to original method call , CustomerService
Object result = methodInvocation.proceed();
// same with AfterReturningAdvice AfterReturningAdvice
System.out.println("CustomerService : Before after CustomerService!");
return result;
} catch (IllegalArgumentException e) {
// same with ThrowsAdvice ThrowsAdvice
System.out.println("CustomerService : Throw exception CustomerService!");
throw e;
}
}
}
spring-aop.xmlを配置します.
customerAdvisor
最後のテスト手順は以下の通りです.package test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import testaop.CustomerService;
/**
*
* @author Administrator
*
*/
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext context = new ClassPathXmlApplicationContext("spring-aop.xml");
CustomerService obj = (CustomerService) context.getBean("customerInterceptorProxy");
System.out.println("****************");
obj.printName();
System.out.println("****************");
obj.printURL();
System.out.println("****************");
}
}
出力結果:****************
Method name : printName
Method arguments : []
CustomerService: Before method CustomerService!
Customer name my name is youshuai
CustomerService : Before after CustomerService!
****************
Customer website : http://www.remote3c.com
****************