liguofeng29’s blog

個人勉強用ブログだっす。

S2AOP - 独自InterType

 独自にInterTypeを作成する場合は、次のインターフェースまたは、抽象クラスを実装します。

 
org.seasar.framework.aop.InterType
org.seasar.framework.aop.intertype.AbstractInterType

空クラスにメソッドを追加してみる。

app.dicon
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE components PUBLIC "-//SEASAR//DTD S2Container 2.4//EN"
<components>
  <component name="myInterType" class="MyInterType" />
 
  <component name="testMyInterType" class="TestMyInterType">
    <interType>myInterType</interType>
  </component>
</components>

MyInterceptor.java
import javassist.CannotCompileException;
import javassist.NotFoundException;
 
import org.seasar.framework.aop.intertype.AbstractInterType;
 
// 独自AOP
public class MyInterType extends AbstractInterType{
 
    private static final long serialVersionUID = 1L;
 
    @Override
    protected void introduce() throws CannotCompileException, NotFoundException {
        // メソッド追加
        addMethod("public void hello() {" +
                      "System.out.println(\"InterTypeテストメッセージです。\");" +
                  "}"
                );
    }
}

TestMyInterType.java
public class TestMyInterType {
 // 空クラス
}
 
 
TestAopMain.java
import java.lang.reflect.Method;
 
import org.seasar.framework.container.SingletonS2Container;
import org.seasar.framework.container.factory.SingletonS2ContainerFactory;
import org.seasar.framework.util.tiger.ReflectionUtil;
 
public class TestMyInterTypeMain {
    public static void main(String args) {
        // S2Container初期化
        SingletonS2ContainerFactory.init();
 
        // コンポーネント取得
        TestMyInterType t = SingletonS2Container.getComponent(TestMyInterType.class);
 
        Method method = ReflectionUtil.getMethod(t.getClass(), "hello");
 
        // hello()メソッド呼び出し
        ReflectionUtil.invoke(method, t);
 
        // S2Container破棄
        SingletonS2ContainerFactory.destroy();
    }
}
 
出力メッセージ
InterTypeテストメッセージです。
 

AbstractInterTypeは、フィールドやメソッド,実装するインタフェースを追加するためのユーティリティメソッドを提供します。
以下はその一部です。
 
protected void addField(Class type, String name)
protected void addField(Class type, String name, String init)
protected void addStaticField(Class type, String name)
protected void addStaticField(Class type, String name, String init)
protected void addMethod(String name, String src)
protected void addMethod(Class returnType, String name, String src)
protected void addMethod(String name, Class paramTypes, String src)
protected void addMethod(Class returnType, String name, Class paramTypes, String src)
protected void addStaticMethod(String name, String src)
protected void addStaticMethod(Class returnType, String name, String src)
protected void addStaticMethod(String name, Class paramTypes, String src)
protected void addStaticMethod(Class returnType, String name, Class[] paramTypes, String src)