---
title: "spring2.5学习笔记（八）：配置方式实现AOP"
author: "sfwhhp"
date: "2010-09-18T09:58:19Z"
tags: ["AOP", "XML", "junit", "编程"]
categories: ["企业架构"]
slug: "spring2-5-aop"
draft: false
lastmod: "2010-09-18T09:58:19Z"
id: 766375
url: "https://sfwhhp.iteye.com/blog/766375"
---

学习笔记（七）中，总结了AOP中的基本概念，并用注解的方式实现了AOP。 下面用配置的方式实现，以同注解方式实现比较，从而深入掌握AOP编程。 代码一：接口和实现类 \[code="java"] package cn.itcast.server; public interface IPersonService { public void save(String name); public String getPersonName(Integer id); public void update(String name,Integer id); } \[/code] \[code="java"] package cn.itcast.server.impl; import cn.itcast.server.IPersonService; public class PersonServiceBean2 implements IPersonService { public String getPersonName(Integer id) { System.out.println("这是getPersonName方法"); return "xxx"; } public void save(String name) { // throw new RuntimeException("我是例外"); System.out.println("这是save方法"); } public void update(String name, Integer id) { System.out.println("这是update方法"); } } \[/code] 代码二：拦截器的定义 \[code="java"] package cn.itcast.server; import org.aspectj.lang.ProceedingJoinPoint; public class MyInteceptor2 { public void doAccessCheck(){ System.out.println("这里输出的是前置通知 "); } public void doAfterReturning(){ System.out.println("这里输出的是后置通知 " ); } public void doAfterReturn(){ System.out.println("这里输出的是最终通知"); } public void doAfterThrowing(){ System.out.println("这里输出的是例外通知 "); } public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable{ //判断用户是否具有权限 System.out.println("进入方法"); Object result = pjp.proceed(); System.out.println("退出方法"); return result; } } \[/code] 代码三：配置文件 \[code="xml"] \[/code] 测试类： \[code="java"] package junit.test; import org.junit.BeforeClass; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import cn.itcast.server.IPersonService; public class SpringAOPTest { @BeforeClass public static void setUpBeforeClass() throws Exception { } @Test public void interceptorTest(){ ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml"); IPersonService ipersonService = (IPersonService) ac.getBean("personService2"); ipersonService.update("xxx",2); ipersonService.save("xx"); ipersonService.getPersonName(2); } } \[/code]