`
8366
  • 浏览: 821019 次
  • 性别: Icon_minigender_1
  • 来自: 西安
社区版块
存档分类
最新评论

第17讲 --使用Spring的注解方式实现AOP入门

阅读更多

 

 使用Spring进行面向切面(AOP)编程

 

要进行AOP编程,首先我们要在spring的配置文件中引入aop命名空间:
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
</beans>

 

 

 

Spring提供了两种切面声明方式,实际工作中我们可以选用其中一种:
l基于XML配置方式声明切面。
l
基于注解方式声明切面。
 
首先启动对@AspectJ注解的支持(蓝色部分):
bean.xml
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
 <aop:aspectj-autoproxy/>
<bean id="orderservice" class="cn.itcast.service.OrderServiceBean"/>
<bean id="log" class="cn.itcast.service.LogPrint"/>
</beans>
 下面我们使用spring注解方式完成aop编程
步骤:
(1).导入依赖jar文件
如果使用了切面编程(AOP),还需要下列jar文件
lib/aspectj/aspectjweaver.jar和aspectjrt.jar
lib/cglib/cglib-nodep-2.1_3.jar
如果使用了JSR-250中的注解,如@Resource/@PostConstruct/@PreDestroy,还需要下列jar文件
lib\j2ee\common-annotations.jar
(2) 在bean.xml中 配置上面的aop支持,并且打开  <aop:aspectj-autoproxy/>
(3) 写接口和实现,方便测试
接口 PersionSevice
package cn.com.xinli.service;
public interface PersionSevice
{
 public void save(String name);
 public void update(String name, Integer personid);
 public String getPersonName(Integer personid);
 
}
 
实现 PersionServiceBean
package cn.com.xinli.service.impl;

import org.apache.log4j.Logger;

import cn.com.xinli.service.PersionSevice;
										   
public class PersionServiceBean implements PersionSevice 
{
	Logger log=Logger.getLogger(PersionServiceBean.class);
	

	public String getPersonName(Integer personid) {
		System.out.println("我是getPersonName()方法");
		return "xxx";
	}

	public void save(String name) {
		System.out.println("我是save()方法");
	}

	public void update(String name, Integer personid) {
		System.out.println("我是update()方法");
	}

}	
 
 (4) 建立一个切面类  MyInterceptor (第一次测试的时候我懒得敲代码,直接复制现成的,没注意切面中的方法还有参数
      ,导致报错:实例化不了一个bean, 结果整了1天才发现原因,教训丫....)
 
package cn.com.xinli.service;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
/**
 * 切面
 *
 */
@Aspect
public class MyInterceptor 
{
 /**
  *  1.第一个* 号代表 返回值的类型可以为任意,也可以指定比如 String,Int
  *  2.cn.itcast.service.impl.PersonServiceBean.. 表示对cn.itcast.service.impl.PersonServiceBean
  *    包下及其子包的下都进行拦截(注意是两个.) 如果是一个 . ,那么就拦截这个包下的类,不会去拦截子包
  *  3. .. 后面的 *.* 第一个星号代表类,为星号说明对所有的类都拦截,第二个星号代表方法,为星号代表拦截所有的方法
  *  4. (..) 代表方法的参数为任意,有也可以,没有也可以
  *  5.如果要拦截PersonServiceBean类下所有的业务方法,也可以这么写:
  *  @Pointcut("execution (* cn.itcast.service.impl.PersonServiceBean*.*(..))")
  * 
  */                                               
 @Pointcut("execution(* cn.com.xinli.service.impl.PersionServiceBean*.*(..))")
 private void anyMethod() {}//声明一个切入点
 
 /*对业务方法中只有一个参数的方法实施 前置通知*/
 //@Before("anyMethod() && args(name)")
 
    @Before("anyMethod()")
 public void doAccessCheck() 
 {
  System.out.println("前置通知");
 }
 
 /*在业务方法执行完毕后,后置通知拿到业务的返回值*/
 @AfterReturning(pointcut="anyMethod()",returning="result")
 //@AfterReturning("anyMethod()")
 public void doAfterReturning() {
  System.out.println("后置通知");
 }
 @After("anyMethod()")
 public void doAfter() {
  System.out.println("最终通知");
 }
 /*在出现异常的情况下在例外通知中拿到异常*/
 @AfterThrowing(pointcut="anyMethod()",throwing="e")
 //@AfterThrowing(pointcut="anyMethod()")
 public void doAfterThrowing(Exception e) {
  System.out.println("例外通知:"+ e);
 }
 //环绕通知,固定写法,可以实现上面的所有通知
 @Around("anyMethod()")
 public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable {
  //if(){//判断用户是否在权限
  System.out.println("进入方法");
  Object result = pjp.proceed();
  System.out.println("退出方法");
  //}
  return result;
 }
 
}
 
 
 (5)一定要讲业务bean和切面配置在beans.xml中(也可以使用扫描)
 <aop:aspectj-autoproxy proxy-target-class="true"/> 
            <bean id="myInterceptor" class="cn.com.xinli.service.MyInterceptor"></bean>
        <bean id="personService"     class="cn.com.xinli.service.impl.PersionServiceBean"></bean>
 
 (6) 测试
 
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
		PersionSevice ps=(PersionSevice)ctx.getBean("personService");
		
		ps.save("xxx");
 
(7)结果:
前置通知
进入方法
我是save()方法
后置通知
最终通知
退出方法
 
分享到:
评论

相关推荐

    springlive(共11章)

    11. **第十一章:Spring Cloud** - 微服务概述:介绍微服务架构,以及Spring Cloud在其中的作用。 - Spring Cloud组件:了解Eureka、Zuul、Ribbon、Hystrix等核心组件的用法,构建微服务生态。 通过阅读《Spring...

    Pro Spring3

    #### 七、更多关于 Spring AOP 及注解(第7章) - **高级 AOP 概念**:深入探讨更复杂的 AOP 概念和技术,如动态代理等。 - **注解驱动的 AOP**:介绍如何利用注解来实现 AOP,简化代码编写。 - **案例研究**:通过...

    Pro Spring 3

    - **第17章:使用Spring的Web应用**:讲解Spring MVC框架的应用。 - **第18章:Spring Web Flow与JSF**:探讨Spring Web Flow框架与JSF的集成。 - **第19章:Spring测试**:介绍Spring测试框架的使用方法。 - **第20...

    Spring6_pdf版讲义.pdf

    - **实现方式**:Spring通过代理机制实现AOP。 ### 十五、Spring对事务的支持 - **事务概述**:事务是一系列操作的集合,这些操作要么全部成功,要么全部失败。 - **Spring事务管理**:通过声明式事务管理和编程式...

    [Pro.Spring.3(2012)].Clarence.Ho.文字版

    ### 第17章:使用Spring的Web应用程序 本章专注于Spring MVC框架,讲解了如何使用Spring构建Web应用。读者将学习到Spring MVC的控制器、视图、模型、表单处理、文件上传等功能,以及如何配置Spring MVC来处理HTTP...

    Spring.3.x企业应用开发实战(完整版).part2

    第17章 实战案例开发 17.1 论坛案例概述 17.1.1 论坛整体功能结构 17.1.2 论坛用例描述 17.1.3 主要功能流程描述 17.2 系统设计 17.2.1 技术框架选择 17.2.2 Web目录结构及类包结构规划 17.2.3 单元测试类包结构规划...

    pro spring

    《Pro Spring》详细介绍了Spring配置的各种方式,包括XML配置、注解配置以及Java配置等。通过对这些配置方式的学习,开发者可以更加灵活地管理和组织Spring应用程序的结构。 #### 五、Spring AOP介绍与实践 面向切...

    Manning Spring in Action 3rd Edition pdf

    开发者可以通过实现特定接口或使用注解等方式自定义Bean的生命周期行为。 #### 五、数据库访问与事务管理 - **JDBC支持**:Spring提供了对JDBC的支持,通过Spring JDBC可以更方便地进行数据库操作,同时Spring也...

    Spring3.x企业应用开发实战(完整版) part1

    第17章 实战案例开发 17.1 论坛案例概述 17.1.1 论坛整体功能结构 17.1.2 论坛用例描述 17.1.3 主要功能流程描述 17.2 系统设计 17.2.1 技术框架选择 17.2.2 Web目录结构及类包结构规划 17.2.3 单元测试类包结构规划...

    SSH框架整合源码(包含声明和注解)

    例如,使用`@Service`, `@Repository`, `@Controller`, `@Autowired`等Spring注解,可以简化Spring的配置。Struts2也有如`@Action`, `@Result`等注解。这种方式更简洁,减少了配置文件的依赖,但可能导致代码中包含...

    Spring攻略(第二版 中文高清版).part1

    第3章 Spring AOP和AspectJ支持 112 3.1 启用Spring的AspectJ注解支持 113 3.1.1 问题 113 3.1.2 解决方案 113 3.1.3 工作原理 113 3.2 用AspectJ注解声明aspect 115 3.2.1 问题 115 3.2.2 解决方案...

    Spring攻略(第二版 中文高清版).part2

    第3章 Spring AOP和AspectJ支持 112 3.1 启用Spring的AspectJ注解支持 113 3.1.1 问题 113 3.1.2 解决方案 113 3.1.3 工作原理 113 3.2 用AspectJ注解声明aspect 115 3.2.1 问题 115 3.2.2 解决方案...

    J2EE软件工程师必读书目.

    - 继承与多态的实现方式 - 封装与抽象的原则 - 设计模式在OOP中的应用 #### 16. Java设计模式 - **书籍简介**:本书由Martin Fowler与Kevlin Henney合著,详细介绍了各种设计模式的实现方法及其适用场景。适合...

    java私塾全部笔记

    - 如何使用Spring实现AOP。 #### 十二、EJB3.0 - **EJB3.0简介** - EJB3.0相对于前代的主要改进。 - **SessionBean开发** - Session Bean的类型及其使用方法。 - **EntityBean开发** - Entity Bean的概念及其...

    struts2基础入门pdf,struts2全面介绍

    - **Struts2与IOC**:Struts2内部使用了依赖注入的概念,例如通过配置文件或注解的方式为Action注入依赖对象。 #### 八、Struts2标签 - **标签概述**:Struts2提供了丰富的标签库,用于简化页面开发过程。 - **...

    Struts2轻松入门V3.0.pdf

    - **灵活的配置**:Struts2允许通过XML文件、注解或混合方式来进行配置,提供多种选择以适应不同的开发场景。 - **强大的拦截器机制**:Struts2的拦截器类似于AOP(面向切面编程),可以用来处理事务管理、权限控制...

    java很实用的基础知识

    20. **Spring框架**:Spring是一个广泛使用的Java EE框架,提供了依赖注入、AOP(面向切面编程)、MVC(模型-视图-控制器)和众多企业级功能。 以上就是Java实用基础知识的主要组成部分。掌握这些概念和技术,将为...

Global site tag (gtag.js) - Google Analytics