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( "performance()" )
public void after(){
System.out.println("调用方法后拦截器运行");
}
@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
">
<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();
}
}