java 是一种可以撰写跨平台应用软件的面向对象的程序设计语言,是由 Sun Microsystems 公司于 1995 年 5 月推出的 Java 程序设计语言和 Java 平台(即 JavaEE(j2ee), JavaME(j2me), JavaSE(j2se))的总称。
这篇文章主要介绍了 java Spring AOP 详解及简单实例的相关资料, 需要的朋友可以参考下
一、什么是 AOP
AOP(Aspect Oriented Programming)面向切面编程不同于 OOP(Object Oriented Programming)面向对象编程,AOP 是将程序的运行看成一个流程切面,其中可以在切面中的点嵌入程序。
举个例子,有一个 People 类,也有一个 Servant 仆人类,在 People 吃饭之前,Servant 会准备饭,在 People 吃完饭之后,Servant 会进行打扫,这就是典型的面向切面编程.
其流程图为:
二、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();
- }
来源: http://www.phperz.com/article/17/1226/357133.html