Spring 織入式AOP 實例

Spring 織入式AOP 實例

package cn.com.chujie.spring.springAop;

/**
 * 目標切點類
 */
public interface Performance {
    /**
     * 目標切點方法
     */
    public void perform();
}

package cn.com.chujie.spring.springAop;

import org.springframework.stereotype.Component;
/**
 * 目標切點的實現類
 */
@Component
public class PerformanceImpl implements  Performance {
    @Override
    public void perform() {
        System.out.println("PerformanceImpl.perform()執行");
    }
}
package cn.com.chujie.spring.springAop;

import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;

/**
 * 通知類
 */
@Aspect
public class Audience {
    /**
     * 制定切點的匹配規則
     */
    @Pointcut( "execution(* cn.com.chujie.spring.springAop.Performance.perform(..))" )
    public void performance(){}

    /**
     * after類型的通知
     */
    @After( "performance()" )
    public void after(){
        System.out.println("調用方法後攔截器運行");
    }

    /**
     * before類型的通知
     */
    @Before("performance()")
    public void before(){
        System.out.println("調用方法前攔截器運行");
    }
}

<?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:context="http://www.springframework.org/schema/context"
       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/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        ">
    <!-- 開啓AspectJ自動代理 -->
    <aop:aspectj-autoproxy/>
    <!-- 聲明代理類 -->
    <bean class="cn.com.chujie.spring.springAop.Audience"/>
</beans>
package cn.com.chujie.spring.springAop;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring-mvc.xml" , "classpath:spring-aop.xml","classpath:spring-bean.xml"})
public class AopTest {
    @Autowired
    Performance performanceImpl;
    @Test
    public void audience(){
        Assert.assertNotNull(performanceImpl);
        performanceImpl.perform();
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章