
AOP(アスペクト指向プログラミング)とは?
クラス間に共通する処理を、外だしする実装のことです。
実際に実装してみましょう。
実装イメージをクラス図にすると下記のようになります。
Main.java(実行するメインプログラム)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
package com.springapp; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Main { public static void main(String[] args) { ApplicationContext app = new ClassPathXmlApplicationContext("bean.xml"); //AOP適用前 TestBean bean1 = (TestBean) app.getBean("TestBean"); bean1.HelloWorld(); System.out.println("--------------------"); //AOP適用後 TestBean bean2 = (TestBean) app.getBean("proxyBean"); bean2.HelloWorld(); } } |
TestBean.java(AOPによる処理を注入するBean)
1 2 3 4 5 6 7 8 9 10 11 12 13 |
package com.springapp; public class TestBean { private String helloWorld; public TestBean() { super(); this.helloWorld = "Hello World!"; } public void HelloWorld() { System.out.println(this.helloWorld); } } |
AOPClass.java(注入する処理を定義したクラス。このクラスが今回の肝です。)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
package com.springapp; import java.lang.reflect.Method; import org.springframework.aop.AfterReturningAdvice; import org.springframework.aop.MethodBeforeAdvice; public class AOPClass implements MethodBeforeAdvice, AfterReturningAdvice { @Override public void before(Method method, Object[] args,Object target) throws Throwable { System.out.println("事前処理"); } @Override public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable { System.out.println("事後処理"); } } |
下記二つのインターフェイスを実装しています。
インターフェイス名 | 説明 |
---|---|
MethodBeforeAdvice | AOPで、メソッド実行前に処理を注入するインターフェイスです。「beforeメソッド」を実装します。 |
AfterReturningAdvice | AOPで、メソッド実行後に処理を注入するインターフェイスです。「afterReturningメソッド」を実装します。 |
bean.xml(AOPの設定ファイルです。)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- AOPを使わない場合 --> <bean id="TestBean" class="com.springapp.TestBean" /> <!-- AOP(処理の注入)する場合 --> <!-- AOPのクラス(事前処理、事後処理を定義) --> <bean id="AOPClass" class="com.springapp.AOPClass" /> <bean id="proxyBean" class="org.springframework.aop.framework.ProxyFactoryBean"> <!-- 処理を注入する対象となるクラス --> <property name="target" ref="TestBean"></property> <property name="interceptorNames"> <list> <value>AOPClass</value> </list> </property> </bean> </beans> |
ProxyFactoryBean
設定情報に、「ProxyFactoryBean」というクラスを設定しています。SpringのAOP専用クラスで、AOPを使うためには定義する必要があります。
target
AOPの対象となるクラスを指定します。(ここでは、作成した「TestBean」を指定しています。)
interceptorNames
AOPで処理を注入するクラスを指定できます。listとして複数指定することも可能です。
実行結果
AOP適用後では、処理が注入されていないですが、AOP適用後は、「事前」と「事後」に処理が挿入されているのがわかります。
この記事へのコメントはありません。