一、创建项目
项目名称:spring101003二、添加jar包 1.在项目中创建lib目录 /lib 2.在lib目录下添加相关spring jar包 --用于AspectJ com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar spring-aspects-3.2.0.RELEASE.jar --用于切面编程 com.springsource.org.aopalliance-1.0.0.jar commons-logging.jar junit-4.10.jar log4j.jar --用于切面编程 spring-aop-3.2.0.RELEASE.jar spring-beans-3.2.0.RELEASE.jar spring-context-3.2.0.RELEASE.jar spring-core-3.2.0.RELEASE.jar spring-expression-3.2.0.RELEASE.jar三、添加配置文件 1.在项目中创建conf目录 /conf 2.在conf目录下添加配置文件 配置文件名称:applicationContext.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:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> </beans>四、创建业务bean 1.在src目录下创建业务bean包 包名:cn.jbit.spring101003.service 2.在包下创建业务bean 业务bean名称:UserService.java 业务bean内容: /** * 被代理类 * @author Administrator * */ public class UserService { /** * 3.删除 */ public void delete(){ System.out.println("delete method"); } }五.创建切面 1)在src下创建包 包名:cn.jbit.spring101003.aspect 2)在包下创建自定义切面类 切面名称:MyAspect.java 切面内容: /** * 自定义切面 * @author Administrator * */ @Aspect public class MyAspect { /** * 3.环绕通知 * @throws Throwable */ public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable{ System.out.println("xml环绕通知"); Object obj = proceedingJoinPoint.proceed(); return obj; } }六、在核心配置文件中添加配置信息 <!-- 基于xml --> <!-- 配置目标类 --> <bean id="userservice" class="cn.jbit.spring101003.service.UserService"></bean> <!-- 配置切面 --> <bean id="myaspect" class="cn.jbit.spring101003.aspect.MyAspect"></bean> <!-- 使用切面 --> <aop:config proxy-target-class="false"> <!-- 引用切面 --> <aop:aspect ref="myaspect"> <!-- 准备切点 --> <aop:pointcut expression="execution(* cn.jbit.spring101003.service.UserService.*(..))" id="mypintcut"/> <!-- 3.环绕通知 --> <aop:around method="around" pointcut-ref="mypintcut"/> </aop:aspect> </aop:config>七、测试 1.在项目中创建test目录 /test 2.在test目录中创建测试包 包名:cn.jbit.spring101003.aspect 3.在测试包中创建测试类 测试类名:MyAspectTest.java 测试内容: /** * 测试类 * @author Administrator * */ public class MyAspectTest{ /** * 3.测试环绕通知 */ @Test public void testAround(){ //加载配置文件 ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml"); //根据bean id 获取对象 UserService userService = (UserService) context.getBean("userservice"); //调用保存方法 userService.delete(); } }