springの最初のAOPの例
面に向かってプログラミングして、いろいろな概念を理解します。例えば、面を切ります。
この時新規に作成したプロジェクトは、スプリングのコアパッケージ(core)だけでなく、AOP機能を付加したjarパッケージも追加されます。
次にbeanクラスを作成します
インターフェースを作成します
完全なプロファイルは以下の通りです。
事前通知の実行
comple.sun.springgaop.test.BenImpl.the Method()が実行されています。
この時新規に作成したプロジェクトは、スプリングのコアパッケージ(core)だけでなく、AOP機能を付加したjarパッケージも追加されます。
次にbeanクラスを作成します
インターフェースを作成します
package com.sun.springaop.test;
public interface IBean {
public void theMethod();
}
次に実現クラスを作成します。package com.sun.springaop.test;
public class BeanImpl implements IBean {
@Override
public void theMethod() {
System.out.println(this.getClass().getName()+"."+new Exception().getStackTrace()[0].getMethodName()+"()"+" ");
}
}
事前通知クラスを作成する、すなわち操作前に実行する機能です。package com.sun.springaop.test;
import java.lang.reflect.Method;
import org.springframework.aop.MethodBeforeAdvice;
public class TestBeforeAdvice implements MethodBeforeAdvice {
// method ,args ,target
@Override
public void before(Method m, Object[] args, Object target)
throws Throwable {
System.out.println(" ");
}
}
設定ファイルでは、ブロッキングとbeanの設定を行います。完全なプロファイルは以下の通りです。
<?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-2.0.xsd">
<!-- -->
<bean id="bean"
class="org.springframework.aop.framework.ProxyFactoryBean"
abstract="false" lazy-init="default" autowire="default"
dependency-check="default">
<property name="proxyInterfaces">
<value>com.sun.springaop.test.IBean</value>
</property>
<property name="target">
<ref local="beanTarget" />
</property>
<property name="interceptorNames">
<list>
<value>theAdvisor</value>
</list>
</property>
</bean>
<!-- -->
<bean id="beanTarget" class="com.sun.springaop.test.BeanImpl"
abstract="false" lazy-init="default" autowire="default"
dependency-check="default">
</bean>
<!-- -->
<bean id="theAdvisor"
class="org.springframework.aop.support.RegexpMethodPointcutAdvisor"
abstract="false" lazy-init="default" autowire="default"
dependency-check="default">
<property name="advice">
<ref local="theBeforeAdvice" />
</property>
<property name="pattern">
<value>com\.sun\.springaop\.test\.IBean\.theMethod</value>
</property>
</bean>
<!-- -->
<bean id="theBeforeAdvice"
class="com.sun.springaop.test.TestBeforeAdvice" abstract="false"
lazy-init="default" autowire="default" dependency-check="default">
</bean></beans>
テストクラス:package com.sun.springaop.test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
public class Client {
public static void main(String[] args) {
BeanFactory factory = new XmlBeanFactory(new ClassPathResource("applicationContext.xml"));
IBean x = (IBean) factory.getBean("bean");
x.theMethod();
}
}
実行結果:事前通知の実行
comple.sun.springgaop.test.BenImpl.the Method()が実行されています。