您的位置:首页 > 编程语言 > Java开发

一个简单的Spring AOP

2009-07-01 16:47 357 查看
 目前三大AOP产品:AspectJ、JBoss AOP、Spring AOP。Spring AOP只能拦截至方法,如果需要更细的控制,如属性,字段级的控制,spring 就需要与AspectJ进行结合。AspectJ是一个强大的AOP框架,本例是Spring AOP+AspectJ 实现简单AOP功能。

项目需要加入AspectJ包,至http://www.eclipse.org/aspectj/ 下载最新1.6.5jar包拷贝至lib下。

 

1、原程序功能:吃饭。

2、AOP追加饭前洗手和饭后水果功能。

 

步骤:

1、定义接口:

 

 
public interface GreetingService {
void sayGreeting();
}


 

 

2、实现接口;

 

public class GreetingServiceImpl implements GreetingService{

private String greeting;
public GreetingServiceImpl(){}
public GreetingServiceImpl(String greeting)
{
this.greeting = greeting;

}
public void sayGreeting()
{
System.out.println(greeting);
}
public void setGreeting(String greeting)
{
this.greeting = greeting;
}
}


 

 

 

3、测试类:

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {

/**
* @param args
*/
public static void main(String[] args) throws Exception{

//BeanFactory beanFactory = new XmlBeanFactory(new FileSystemResource("NewFile1.xml"));

ApplicationContext factory = new ClassPathXmlApplicationContext("applicationContext.xml");
GreetingService greetingService = (GreetingService)factory.getBean("greetingService");
greetingService.sayGreeting();
}

}


 

4、通知类

 

public class Minstrel {

public void singBefore()
{
System.out.println("<--饭前洗手!");
}

public void  singAfter()
{
System.out.println("-->饭后水果!");
}
}


 

 

5、配置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:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> <bean id="greetingService" class="com.GreetingServiceImpl">
<property name="greeting" value="开始吃饭!"/>
</bean>
<bean id="minstrel" class="com.Minstrel"/>
<aop:config>
<aop:aspect ref="minstrel" >
<aop:pointcut  id="questPointcut" expression="execution(* *.sayGreeting())" />
<aop:before
method="singBefore"
pointcut-ref="questPointcut"
/>
<aop:after
method="singAfter"
pointcut-ref="questPointcut"
/>
</aop:aspect>
</aop:config>


 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息