AOP切面用aspectjweaver.jar实现代码

来源:互联网 发布:淘宝能买到氰化钾吗 编辑:程序博客网 时间:2024/06/01 08:58

一、导入aspectjweaver.jar包

 

二、创建一个类,使在执行方法之前之后调用


package com.ly.spring.aop.advice;public class AdviceRound {/*创建两个方法,方法名随意,这里为方便区分,设为before即执行方法之前调用,after即执行方法之后调用*/ public void before(){ System.out.println("before之前调用"); } public void after(){ System.out.println("after之后调用"); }}

三、创建一个类。定义两个方法,当调用这些方法时,会使之之前调用before方法,之后调用after方法

 

  

package com.ly.spring.aop.AspectService.impl;import com.ly.spring.aop.AspectService.AspectService;public class AspectServiceImpl implements AspectService{@Overridepublic void print(String message) {System.out.println(message);}@Overridepublic void save() {System.out.println("调用了save方法");} }

四、创建spring中bean配置,需加入xmlns:aop="http://www.springframework.org/schema/aop"               http://www.springframework.org/schema/aop
             http://www.springframework.org/schema/aop/spring-aop-4.2.xsd">


<?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"xsi:schemaLocation="         http://www.springframework.org/schema/beans             http://www.springframework.org/schema/beans/spring-beans.xsd             http://www.springframework.org/schema/context             http://www.springframework.org/schema/context/spring-context.xsd             http://www.springframework.org/schema/aop             http://www.springframework.org/schema/aop/spring-aop-4.2.xsd"><!--目标对象 --><bean id="aspectservice" class="com.ly.spring.aop.AspectService.impl.AspectServiceImpl"/><!-- advice通知 --><bean id="adviceMessage" class="com.ly.spring.aop.advice.AdviceRound"></bean><!-- aspectjweaver.jar中为以下配置 --><aop:config>  <aop:aspect id="myaspect" ref="adviceMessage">    <!-- aop切点格式       匹配com.ittx.spring.aopservice.impl包下所有的类的所有方法。。         第一个*代表所有的返回值类型 第二个*代表所有的类 第三个*代表类所有方法 最后一个..代表所有的参数。也可以直接定位到此类的某个方法execution(* com.ly.spring.aop.AspectService.impl.AspectServiceImpl.print(..))-->    <aop:pointcut id="myPointcut" expression="execution(* com.ly.spring.aop.AspectService.impl.*.*(..))" />    <!--  pointcut-ref=""里面填的为 aop:pointcut中的id值-->    <aop:before method="before" pointcut-ref="myPointcut"/>    <aop:after method="after" pointcut-ref="myPointcut"/>  </aop:aspect></aop:config></beans>

五、以下为测试类


package junittest;import static org.junit.Assert.*;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import com.ly.spring.aop.AspectService.AspectService;public class aoptest {@Testpublic void test() {ApplicationContext context=new ClassPathXmlApplicationContext("springBeans.xml");AspectService aspectService=(AspectService) context.getBean("aspectservice");aspectService.print("执行打印message代码");aspectService.save();}}