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;

/**
 * 通知類接口
 */
public interface Encoreable {
    void performEncore();
}

package cn.com.chujie.spring.springAop;

/**
 * 通知實現類
 */
public class DefaultEncoreable implements Encoreable {
    @Override
    public void performEncore() {
        System.out.println("DefaultEncoreable.performEncore()");
    }
}

package cn.com.chujie.spring.springAop;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.DeclareParents;

/**
 * 引入式AOP
 */
@Aspect
public class EncoreableIntroducer {
    @DeclareParents( value = "cn.com.chujie.spring.springAop.Performance+",
            defaultImpl = DefaultEncoreable.class )
    public static Encoreable encoreable;
}

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();
        Encoreable encoreable = (Encoreable)performanceImpl;
        encoreable.performEncore();
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章