AOPをちょっとためしてみた
Adviceを作ってみる
package org.sample.spring; import org.aspectj.lang.ProceedingJoinPoint; public class TraceAdvice { public void around(ProceedingJoinPoint pjp) throws Throwable { System.out.println("before"); pjp.proceed(); System.out.println("after"); } }
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" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd"> <aop:config> <aop:aspect id="myAspect" ref="myAdvice"> <aop:pointcut id="myAspectPc" expression="execution(* org.sample..*.greet(..))" /> <aop:around pointcut-ref="myAspectPc" method="around" /> </aop:aspect> </aop:config> <bean id="messenger" class="org.sample.spring.MessengerImpl"> <property name="message" value="Hello world"></property> </bean> <bean id="myAdvice" class="org.sample.spring.TraceAdvice" /> </beans>
MessengerとMessengerImplは簡単に
package org.sample.spring; public interface Messenger { void greet(); }
package org.sample.spring; public class MessengerImpl implements Messenger { private String message; public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public void greet() { System.out.println(message); } }
メインをこんな感じに
package org.sample.spring; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Main { public static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext( "applicationContext.xml"); Messenger bean = (Messenger) ctx.getBean("messenger"); bean.greet(); } }
実行すると
before Hello world after
こんな具合。
アスペクト成功〜。