从spring in action上试了一下例子,运行不起来,书上写得又很简略,无语,只能来这里示救啦
首先我定义了一个表演者类
package com.mai.aop;public class Performer {
public void perform() {
System.out.println("Starting to perform!!!");
}
}又定义了一个观众类
package com.mai.aop;public class Audience {
public void takeSeats() {
System.out.println("the audience are taking their seats!!");
}

public void turnOffCellPhone() {
System.out.println("the audience are turning off their cell phone!!");
}

public void applaud() {
System.out.println("the audience are applaud!!");
}
}接着使用配置文件配置切面
<?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-2.0.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
<bean id="audience" class="com.mai.aop.Audience"/>
<bean id="Performer" class="com.mai.aop.Performer"/>
<aop:config>
<aop:aspect ref="audience">
<aop:pointcut id="performance" expression="execution(* *.perform(..))"/>
<aop:before method="takeSeats" pointcut-ref="performance"/>
<aop:before method="turnOffCellPhone" pointcut-ref="performance"/>
<aop:after-returning method="applaud" pointcut-ref="performance"/>
</aop:aspect>
</aop:config>
</beans>最的是写了一个测试类作测试用
package com.mai.aop;import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;public class Tester { /**
 * @param args
 */
public static void main(String[] args) {
// TODO Auto-generated method stub
XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource("com/mai/aop/aop.xml"));
Performer performer = (Performer) factory.getBean("Performer");
performer.perform();
}}
结果输出:
May 21, 2009 11:57:39 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [com/mai/aop/aop.xml]
Starting to perform!!!
感觉那个切面根本没有起作用,但却又报任何的错,完全不清楚哪里有问题,请牛人帮忙看看啊

解决方案 »

  1.   

    不好意思,刚试了一下,不用XmlBeanFactory,改用ClassPathXmlApplicationContext就可以啦,真神奇啊
      

  2.   

    并不神奇,BeanFactory是不支持aop的,spring的文档中说的很清楚:3.8.1. BeanFactory 还是 ApplicationContext?
    简单的说:除非你有更好的理由,否则尽量使用ApplicationContext,下面是对于哪些"为什么"等等更深入的建议ApplicationContext包含BeanFactory的所有功能。通常建议比BeanFactory优先,除非有一些限制的场合如字节长度对内存有很大的影响时(Applet)。然后,绝大多数"典型的"企业应用和系统,ApplicationContext就是你需要使用的。Spring2.0及以上版本,大量使用了link linkend="beans-factory-extension-bpp">BeanPostProcessor扩展(以便应用代理等功能),如果你选择BeanFactory则无法使用相当多的支持功能,如事务和AOP,这可能会导致混乱,因为配置并没有错误。
      

  3.   

    一直都是用ClassPathXmlApplicationContext这个啊
    楼主写的XmlBeanFactory这个没见过诶
    感觉很奇怪
      

  4.   

    XmlBeanFactory是BeanFactory关于xml的实现啊