Spring 4初识aop

来源:互联网 发布:淘宝优惠券大小尺寸 编辑:程序博客网 时间:2024/06/06 00:48

aop:面向切面编程,以前的编程都是从上往下顺序执行,我对于aop的理解,就是像一个圆柱形,横着切一刀,在他原来的地方的前,后,等多个位置,自己加载上另外的方法,使其更加强大。

其中有多个东西,jointpoint,切面切点等;

案例:spring创建的bean中,在xml文件进行配置。

切面:

public class advice {    //切面    private void dobefore(JoinPoint jp) {        System.out.println(jp.getClass());        System.out.println("dobefore....");    }    private void doafter() {        // TODO Auto-generated method stub        System.out.println("doafter....");    }}
bean:

public class aopServiceImpl implements aopService{    @Override    public void doing() {            System.out.println("doing....");    }}
xml文件:

  <aop:config>  <aop:aspect id="qiemian" ref="advice">  <aop:pointcut expression="execution(* com.cai.service.*.*(..))" id="qiedian"/>  <aop:before method="dobefore" pointcut-ref="qiedian"/>   </aop:aspect>  </aop:config>    <bean id="advice" class="com.cai.aop.advice" ></bean>    <bean id="aopService" class="com.cai.service.impl.aopServiceImpl"></bean>
execution表达式( 返回值 扫描的包 (参数--两个点为不限制参数个数等))

test:

public class aoptest {    public static void main(String[] args) {        ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");        aopService aop=(aopService) ac.getBean("aopService");        aop.doing();//      test t1= (test) ac.getBean("mytest");//       t1.mydo();    }}
在切面里定义切点,然后调用方法,意思就是com.cai.service.*.*里的类建出的springbean,都会执行前调用dobefore方法

直接创建类test,不实现接口的方式调用,失败了,没有调用dobefore方法,看来基层结构还是需要研究才能学懂。


前置通知,后置通知差不多

有个环绕通知:

public Object doAround(ProceedingJoinPoint pjp) throws Throwable{System.out.println("添加学生前");Object retVal=pjp.proceed();System.out.println(retVal);System.out.println("添加学生后");return retVal;}

实现结果是:前置,环绕前置,过程,环绕后置,后置


原创粉丝点击