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

Spring Aop demo 博客分类: Spring Spring Aop demoaop切面编程配置文件aop例子

程序员文章站 2024-03-15 13:18:47
...

做了个Spring Aop的Demo,记录一下。

 

在Sping Bean的基础上,增加“观众”的角色,观众在观看表演之前,要就坐,关掉手机,观看之后,鼓掌或者对表演不满,要求退票。

package com.audience;

public class Audience {
	public  void takeSeat() {
		System.out.println("take seat");
	}
	
	public void turnOffPhone() {
		System.out.println("turn off phone");
	}
	
	public void applaud() {
		System.out.println("applaud");
	}
	
	public void demandRefund() {
		System.out.println("demand refund");
	}
}

 

配置文件,如下所示

<?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:context="http://www.springframework.org/schema/context"
	xmlns:p="http://www.springframework.org/schema/p"
	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">
           

<bean id="duke" class="com.performer.service.impl.PoeticJuggler">
	<constructor-arg value="15"></constructor-arg>
	<constructor-arg ref="sonnet"></constructor-arg>
</bean>

<bean id="jake" class="com.performer.service.impl.Instrumentalist"
	p:song = "little star"
	p:instrument-ref = "piano" />

<bean id="audience" class="com.audience.Audience"></bean>
<bean id="sonnet" class="com.poem.service.impl.Sonnet"></bean>
<bean id="piano" class="com.instrument.service.impl.Piano"></bean>

<aop:config>
	<aop:aspect ref="audience">
		<aop:pointcut expression="execution(* *.perform(..))" id="a"/>
		<aop:before pointcut-ref="a" method="takeSeat"/>
		<aop:before pointcut-ref="a" method="turnOffPhone"/>
		<aop:after-returning pointcut-ref="a"  method="applaud"/>
		<aop:after-throwing pointcut-ref="a" method="demandRefund"/>
	</aop:aspect> 
</aop:config>
</beans>

 

运行结果,如下图所示

Spring Aop demo
            
    
    博客分类: Spring Spring Aop demoaop切面编程配置文件aop例子

另附源码

  • Spring Aop demo
            
    
    博客分类: Spring Spring Aop demoaop切面编程配置文件aop例子
  • 大小: 96 KB