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

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

今回は、前回のサンプル・ライブラリに対するアスペクト・ライブラリを作成しましょう。 プロジェクト名は「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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值