spring Aop 面向切面编程简单实例

最近画了一点时间研究了一下spring的aop,接下来就先直接放源码:
首先创建一个教师Teacher接口:

package com.sise.aop;
public interface Teacher {
    public void teach();
}

然后是一个教师类:

package com.sise.aopimpl;

import com.sise.aop.Teacher;

public class TeacherImpl implements Teacher{

    @Override
    public void teach() {
        // TODO Auto-generated method stub
        System.out.println("教师开始教课");
    }
}

然后再是写一个学生类:

package com.sise.aopimpl;

public class Student {

    public Student() {
        // TODO Auto-generated constructor stub
    }
    public void seats()
    {
        System.out.println("学生回到教室");   
    }
    public void sayhello()
    {
        System.out.println("向老师问好");
    }
    public void ask()
    {
        System.out.println("上课提问");
    }
    public void endclass()
    {
        System.out.println("下课了");
    }
}

接下来我们希望在做后期维护的时候能够在教师执行teach方法之前执行student类里面的seats和sayhello方法,在教师执行完teach方法之后执行endclass方法。对于这种情况,在spring里面提供了一种叫做aop的方法来执行;
以下是我的beans.xml的配置文件内容:


<beans
    xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
     http://www.springframework.org/schema/aop   
    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"
    xmlns:aop="http://www.springframework.org/schema/aop"
    >  
    

    
    <bean id="TeacherImpl" class="com.sise.aopimpl.TeacherImpl"/>  

      
    <bean id="Student" class="com.sise.aopimpl.Student">bean>  

      
    <aop:config proxy-target-class="true">
        <aop:aspect ref="Student">  
              
            <aop:before pointcut="execution(* com.sise.aopimpl.TeacherImpl.teach(..))" method="seats"/>  
              
            <aop:before pointcut="execution(* com.sise.aopimpl.TeacherImpl.teach(..))" method="sayhello"/>  

              
            <aop:after-returning pointcut="execution(* com.sise.aopimpl.TeacherImpl.teach(..))" method="ask"/>  

              
            <aop:after-throwing pointcut="execution(* com.sise.aopimpl.TeacherImpl.teach(..))" method="endclass"/>  
        aop:aspect>  
    aop:config>  

beans>

beans.xml所放置的位置如下图所示:

spring Aop 面向切面编程简单实例_第1张图片

接下来在一个便是测试部分的代码:

package com.sise.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.sise.aopimpl.TeacherImpl;


public class Test {

    public static void main(String[] args)
    {
        ApplicationContext apc=new ClassPathXmlApplicationContext("beans.xml");
        TeacherImpl teacher=(TeacherImpl) apc.getBean("TeacherImpl");
        teacher.teach();
    }
}

最后是运行结果的截图:
这里写图片描述

你可能感兴趣的:(spring)