Java--簡單的Spring AOP配置以及AOP事物管理,JDK/GCLib動態代理

高洛峰
發布: 2016-10-13 10:01:43
原創
1951 人瀏覽過

一、看一下簡單的透過XML的AOP配置

1.首先創建一個簡單的Student類

public class Student {
    private Integer age;
    private String name;

    public void setAge(Integer age) {
        this.age = age;
    }

    public Integer getAge() {
        System.out.println("Age : " + age);
        return age;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        System.out.println("Name : " + name);
        return name;
    }

    public void printThrowException() {
        System.out.println("Exception raised");
        throw new IllegalArgumentException();
    }
}
登入後複製

2.創建一個簡單的aspect切面class

public class Logging {/**
     * This is the method which I would like to execute
     * before a selected method execution.
     */public void beforeAdvice() {
        System.out.println("Going to setup student profile.");
    }

    /**
     * This is the method which I would like to execute
     * after a selected method execution.
     */public void afterAdvice() {
        System.out.println("Student profile has been setup.");
    }

    /**
     * This is the method which I would like to execute
     * when any method returns.
     */
    public void afterReturningAdvice(Object retVal) {
        System.out.println("Returning:" + retVal.toString());
    }

    /**
     * This is the method which I would like to execute
     * if there is an exception raised.
     */
    public void AfterThrowingAdvice(IllegalArgumentException ex) {
        System.out.println("There has been an exception: " + ex.toString());
    }
}
登入後複製

3.SpringAOP.xml配置

reee execution(* com.seeyon.SpringBean.aop.Student.get*(..))切點表達式:

(1)第一個*代表方法的回傳值是任意的

(2)get*代表以get開頭的所有方法

(3)(..)代表方法的參數為任意個數

 

4.main方法

<bean id="student" class="com.seeyon.SpringBean.aop.Student" p:name="yangyu" p:age="27"></bean>
    <bean id="logging" class="com.seeyon.SpringBean.aop.Logging"></bean>

    <!--XML方式配置Spring AOP-->
    <aop:config>
        <aop:aspect id="log" ref="logging">   【切面class】
            <aop:pointcut id="studentMethod" expression="execution(* com.seeyon.SpringBean.aop.Student.get*(..))"/> 【切点】
            <aop:before pointcut-ref="studentMethod" method="beforeAdvice"/>  【方法执行之前触发切面class的beforeAdvice方法】
            <aop:after pointcut-ref="studentMethod" method="afterAdvice"/>    【方法执行之后触发切面class的afterAdvice方法】
        </aop:aspect>
    </aop:config>
登入後複製

5.輸出結果

public class test {
    public static void main(String[] args) {
        ApplicationContext context =
                new ClassPathXmlApplicationContext("SpringAop.xml");
        Student student = (Student) context.getBean("student");
        student.getName();
//        student.getAge();
//        student.printThrowException();
    }
}
登入後複製
 

1.先建立一個簡單的Student類別(同一.1中,請看上面

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板