SSブログ

Spring AOP のサンプルを作ってみる [開発]

AOP はAspect Oriented Programming (アスペクト指向プログラミング) の略です。横断的関心事を自身のコードから分離させるための仕組みのようです。たとえばメソッドの最初と最後にログを仕込みたい場合、通常メソッドの最初と最後にログ処理を埋め込むと思いますが、AOP実装時はこの処理を埋め込みません。その代り、アプリケーション起動時にこの処理が各メソッドの最初と最後に織り込まれる仕組みになっているようです。

下記はテストで作ったサンプルアプリです。Spring ではアノテーションを使ったやり方もありますが、今回はあえてXMLベースの実装を備忘録として残します(少し苦労したので・・・[たらーっ(汗)])。

(1) Maven で下記依存を追加します。
groupId:org.springframework
artifactId:spring-context
version:4.0.6.RELEASE
groupId:org.springframework
artifactId:spring-aspects
version:4.0.6.RELEASE

(2) Springの設定ファイル (applicationContext.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:aop="http://www.springframework.org/schema/aop"
  xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">

  <!-- ターゲット -->
  <bean id="bean" class="sample.BeanImpl">
    <property name="msg" value="Hello!" />
  </bean>

  <!-- Aspect と Pointcut の定義 -->
  <aop:config>
    <aop:aspect id="loggingAspect" ref="loggingAdvice">
      <aop:pointcut id="loggingPointcut"
          expression="execution(* sample.*.*(..))" />
      <aop:around pointcut-ref="loggingPointcut"
          method="loggingAround" />
    </aop:aspect>
  </aop:config>

  <!-- Advise の定義 -->
  <bean id="loggingAdvice" class="sample.Logging" />
</beans>

(3) Advice を作成します。
package sample;
import org.aspectj.lang.ProceedingJoinPoint;

public class Logging {
  public Object logAround(ProceedingJoinPoint pjp) throws Throwable {
    System.out.println("[Logging] 前処理");
    Object retVal = pjp.proceed();
    System.out.println("[Logging] 後処理");
    return retVal;
  }
}

(4) Target を作成します。
・インタフェース
package sample;

public interface Bean {
  void hello();
}

・実装クラス
package sample;

public class BeanImpl implements Bean {
  private String msg;

  public void setMsg(String msg) {
    this.msg = msg;
  }

  @Override
  public void hello() {
    System.out.println(msg);
  }
}

(5) 動作確認用コードを作成します。
package sample;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

public class SampleMain {
  public static void main(String[] args) {
    ApplicationContext ac = new FileSystemXmlApplicationContext(
            "src/main/webapp/WEB-INF/applicationContext.xml");
    Bean bean = (Bean) ac.getBean("bean");
    bean.hello();
  }
}



Java・J2EE・オープンソース Spring入門 ~より良いWebアプリケーションの設計と実装

Java・J2EE・オープンソース Spring入門 ~より良いWebアプリケーションの設計と実装

  • 作者: 長谷川 裕一
  • 出版社/メーカー: 技術評論社
  • 発売日: 2005/04/16
  • メディア: 単行本

nice!(0)  コメント(0) 
共通テーマ:blog

nice! 0

コメント 0

コメントを書く

お名前:[必須]
URL:
コメント:
画像認証:
下の画像に表示されている文字を入力してください。

珍しい来訪者Struts 2 の Action クラ.. ブログトップ

この広告は前回の更新から一定期間経過したブログに表示されています。更新すると自動で解除されます。