public class Book { public void add(){ System.out.println("Book裏面的add方法"); } }
public class MyBook { public void before1(){ System.out.println("MyBook中的before方法"); } }
<bean id="book" class="com.xiaobo.aop.Book"></bean> <bean id="myBook" class="com.xiaobo.aop.MyBook"></bean> <!--配置aop操做--> <aop:config> <!--配置切入點--> <aop:pointcut id="point1" expression="execution(* com.xiaobo.aop.Book.*())" ></aop:pointcut> <!--配置切面 把加強用到方法後面 --> <aop:aspect ref="myBook"> <!--配置加強類,method爲加強類中哪一個方法爲前置--> <aop:before method="before1" pointcut-ref="point1"></aop:before> </aop:aspect> <aop:aspect ref="myBook"> <!--配置加強類,method爲加強類中哪一個方法爲前置--> <aop:after method="before1" pointcut-ref="point1"></aop:after> </aop:aspect> </aop:config>
@Test public void testaop(){ ApplicationContext context=new ClassPathXmlApplicationContext("bean2.xml"); Book book = (Book) context.getBean("book"); book.add(); }
<!--配置對象--> <bean id="book" class="com.xiaobo.aop.Book"></bean> <bean id="myBook" class="com.xiaobo.aop.MyBook"></bean> <!--一句話自動開啓註解aop操做--> <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
//定義切面 @Aspect public class Book { //定義要以特定加強的方式的加強方法,book先執行 @Before(value = "execution(* com.xiaobo.aop.MyBook.*(..))") public void add(){ System.out.println("Book裏面的add方法"); } }
public class MyBook { public void before1(){ System.out.println("MyBook中的before方法"); } }
@Test public void testaop2(){ ApplicationContext context=new ClassPathXmlApplicationContext("bean3.xml"); MyBook book = (MyBook) context.getBean("myBook"); book.before1(); }