1、环境
eclipse、spring-dist下所有jar、aopalliance.jar、aspectjrt.jar、aspectjweaver.jar、cglib-nodep.jar、commons-logging.jar
另:java 1.7以上版本用aspectj 1.7.2以上版本
2、项目搭建:
Java项目名:AopInAnnotaion
src下包:com.wind.beans、com.wind.interceptor、com.wind.test
资源文件夹:Resource
3、相关代码:
com.wind.beans.SimpleBeans:
package com.wind.beans;
import org.springframework.stereotype.Component;
@Component
public class SimpleBean {
public void f(){
System.out.println("SimpleBean.f");
}
}
com.wind.Interceptor:
package com.wind.interceptor;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class SimpleInterceptor {
//SimpleBean包下所有方法
@Pointcut("execution(* com.wind.beans.SimpleBean.*(..))")
public void anyMethod(){}
//引用上边的pointcut签名
@Before("anyMethod()")
public void p(){
System.out.println("anyMethod");
}
}
com.wind.test.AopTest:
package com.wind.test;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.wind.beans.SimpleBean;
public class AopTest {
@Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:aop.xml");
SimpleBean sBean = (SimpleBean) context.getBean("simpleBean");
sBean.f();
}
}
Resource资源文件夹下配置文件:aop.xml:
<?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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<!-- 激活AOP -->
<aop:aspectj-autoproxy />
<!-- 激活Bean扫描 -->
<context:component-scan base-package="com.wind.*" />
</beans>
4、运行测试:
运行com.wind.test.AopTest类,出现
anyMethod
SimpleBean.f
说明成功。