温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Spring AOP如何在java项目中使用

发布时间:2020-11-18 16:39:26 来源:亿速云 阅读:190 作者:Leah 栏目:编程语言

这篇文章将为大家详细讲解有关Spring AOP如何在java项目中使用 ,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

一、什么是AOP

  AOP(Aspect Oriented Programming)面向切面编程不同于OOP(Object Oriented Programming)面向对象编程,AOP是将程序的运行看成一个流程切面,其中可以在切面中的点嵌入程序。

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

  其流程图为:

  Spring AOP如何在java项目中使用

二、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中进行配置:

<&#63;xml version="1.0" encoding="UTF-8"&#63;>
<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();
 }

关于Spring AOP如何在java项目中使用 就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI