倭マン's BLOG

くだらない日々の日記書いてます。 たまにプログラミング関連の記事書いてます。 書いてます。

アスペクト・ライブラリを作る 其ノ弐 -- 「アスペクト・ライブラリ」プロジェクト

今回は、前回のサンプル・ライブラリに対するアスペクト・ライブラリを作成しましょう。 プロジェクト名は「greeting-lib」とします。

pom.xml


とりあえずサンプルを。

<project>
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.sample</groupId>
  <artifactId>greeting-lib</artifactId>
  <packaging>jar</packaging>
  <version>0.1</version>

  <dependencies>
    <dependency>
      <groupId>org.sample</groupId>
      <artifactId>greeting</artifactId>
      <version>0.1</version>
    </dependency>

    <dependency>
      <groupId>aspectj</groupId>
      <artifactId>aspectjrt</artifactId>
      <version>1.5.2a</version>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>aspectj-maven-plugin</artifactId>
          
        <configuration>
          <weaveDependencies>
            <waveDependency>
              <groupId>org.sample</groupId>
              <artifactId>greeting</artifactId>
            </waveDependency>
          </weaveDependencies>
        </configuration>
          
        <executions>
          <execution>
            <goals>
              <goal>compile</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>

注意点をいくつか:

  • 拡張機能を付け加える対象となるプロジェクト(今の場合「greeting」プロジェクト)への依存性を付加します。
  • aspectjrt への依存性を付加します(AspectJ プロジェクトには必須)。
  • aspectj-maven-plugin の <executions> 要素を設定します(プロジェクトのビルド時に「織り込み」を行うために必要)。
  • aspectj-maven-plugin の <weaveDependency> 要素(configuation/weaveDependencies/weaveDependency 要素)を設定します。

最後の <weaveDependency> 要素の設定は、外部ライブラリにアスペクトを織り込むのに必要となります*1

AspectJ アスペクト:Narration


Narration アスペクトは Person#greet() メソッドが呼び出されたとき、それを誰が言ったのか付け加えるアスペクトです。 もう少し具体的に言えば、Person#greet() が呼び出されたとき、「Hello, world !」というメッセージの前に「《名前》+ "says : "」という文字列を付け加えます:

package greeting;

public aspect Narration{

    before(Person person):
            execution(* Person.greet()) && this(person){
        System.out.print(person.getName()+" says : ");
    }
}

ローカル・リポジトリへインストール


プロジェクトが完成したら、ローカル・リポジトリへインストールしましょう:

mvn clean install

*1:Eclipse 上で開発する場合には同様の設定が必要になります。 この設定はプロジェクトの「Properties」から行います。 詳しくはそのうちに。