學習筆記,每一天我們都在進步。
2007/03/26 01:58
首先来2个最简单的bean
[codes=java]
package example;

/**
* @author jockhuang
*
*/
public class TestA {

  public void sayHello(){
    System.out.println("TestA");
  }
  

}
[/codes]

[codes=java]
package example;

public class TestB {
  public void sayHi(){
    System.out.println("TestB");
  }
}
[/codes]
2个很简单的bean,applicationContext.xml中的配置如下:
[codes=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-2.0.xsd  
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
  <bean id="TestA" class="example.TestA"></bean>
  <bean id="TestB" class="example.TestB"></bean>
</beans>
[/codes]
来个测试运行这2个bean
[codes=java]
package example;  
  
import org.springframework.context.ApplicationContext;  
import org.springframework.context.support.ClassPathXmlApplicationContext;  

  
public final class TestAOP {  
  
    public static void main(String[] args) {  
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");  
        TestA a = (TestA) ctx.getBean("TestA");  
        a.sayHello();  
        TestB b = (TestB) ctx.getBean("TestB");  
        b.sayHi();  
    }  
  
}  
[/codes]

这个小程序执行结果应该很明白了。
AOP上场了。
[codes=java]
package example;

import org.aspectj.lang.annotation.AfterReturning;  
import org.aspectj.lang.annotation.Aspect;  
import org.aspectj.lang.annotation.Pointcut;  
  
@Aspect
public class SimpleAspect {  
  
    @Pointcut("execution(* example.*.*H*())")  
    public void simplePointcut() { }  
      
    @AfterReturning(pointcut="simplePointcut()")  
    public void simpleAdvice() {  
        System.out.println("I am ghost!");  
    }  
}  
[/codes]
applicationContext.xml修改为
[codes=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-2.0.xsd  
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
  <aop:aspectj-autoproxy />
  <bean id="TestA" class="example.TestA"></bean>
  <bean id="TestB" class="example.TestB"></bean>
  <bean id="simpleAspect" class="example.SimpleAspect" />
</beans>
[/codes]

还是那个TestAOP,现在的执行结果变成;
TestA
I am ghost!
TestB
I am ghost!

AOP,AOP
最近看Spring好晕好晕,需要高人指点一下迷津了。
发表评论
表情
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
打开HTML
打开UBB
打开表情
隐藏
记住我
昵称   密码   游客无需密码
网址   电邮   [注册]