欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java Spring AOP详解及简单实例

程序员文章站 2024-02-22 19:32:10
一、什么是aop   aop(aspect oriented programming)面向切面编程不同于oop(object oriented programm...

一、什么是aop

  aop(aspect oriented programming)面向切面编程不同于oop(object oriented programming)面向对象编程,aop是将程序的运行看成一个流程切面,其中可以在切面中的点嵌入程序。

  举个例子,有一个people类,也有一个servant仆人类,在people吃饭之前,servant会准备饭,在people吃完饭之后,servant会进行打扫,这就是典型的面向切面编程.

  其流程图为:

  java Spring AOP详解及简单实例

二、spring aop实现:

1、people类:

public class people {

 public void eat() {
 system.out.println(“happyheng开始吃饭啦");
 }

 public void play(){
 
 }
}

servant类:

@aspect
public class servant {

 /**
 * 在吃饭之前
 */
 @before("execution(** com.happyheng.entity.people.eat(..))")
 public void preparefood(){
 system.out.println("准备食物");
 }

 /**
 * 在吃饭之后
 */
 @after("execution(** com.happyheng.entity.people.eat(..))")
 public void clean(){
 system.out.println("打扫");
 }

}

其中的 @before是指执行前,@after是指执行方法后获取方法抛出异常后,@afterreturning是指在执行方法后调用,@afterthrowing是指方法抛出异常后调用。

2、在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:aop="http://www.springframework.org/schema/aop"
xsi:schemalocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-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/context 
http://www.springframework.org/schema/context/spring-context-3.0.xsd"
xmlns:context="http://www.springframework.org/schema/context">
<context:component-scan base-package="com.happyheng" />
<aop:aspectj-autoproxy />
<!--注意aspect的bean必须在spring中注册,否则不会生效,spring会用这个bean进行拦截-->
<bean class="com.happyheng.aop.servant"></bean>
<bean id="happyheng" class="com.happyheng.entity.people"></bean>
</beans>

3、在main中使用:

 public static void main(string[] args) {
 applicationcontext ctx = new classpathxmlapplicationcontext(application_xml);
 
 people happyheng = (people)ctx.getbean("happyheng");
 happyheng.eat();
 }

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!