1.业务类
package cn.blogjava.aop;

public class HelloSpeaker implements IHello {

    
public void hello(String name) {
        System.out.println(
"Hello, " + name );
    }
}

2.将要添加Aspect的方法抽象到接口中
package cn.blogjava.aop;

public interface IHello {
    
public void hello(String name);
}

3.实现MethodBeforeAdvice接口,实现log功能
package cn.blogjava.aop;

import java.lang.reflect.Method;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.springframework.aop.MethodBeforeAdvice;

public class LogBeforeAdvice implements MethodBeforeAdvice{
    
    
private Logger logger = Logger.getLogger(this.getClass().getName());
    
    
public void before(Method method, Object[] args, Object targer){
        logger.log(Level.INFO, 
"method starts" + method);
    }
}

4.配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN"
    "http://www.springframework.org/dtd/spring-beans.dtd"
>
<beans>
    
<bean id="logBeforeAdvice" 
        class
="cn.blogjava.aop.LogBeforeAdvice"/>
    
<bean id="helloSpeaker"
        class
="cn.blogjava.aop.HelloSpeaker" />
    
<bean id="helloProxy"
        class
="org.springframework.aop.framework.ProxyFactoryBean">
        
<property name="proxyInterfaces">
            
<value>cn.blogjava.aop.IHello</value>
        
</property>
        
<property name="target">
            
<ref bean="helloSpeaker" />
        
</property>        
        
<property name="interceptorNames">
            
<list>
                
<value>logBeforeAdvice</value>
            
</list>
        
</property>        
    
</bean>
</beans>

5.测试类
package cn.blogjava.aop;

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

public class SpringAopDemo {

    
public static void main(String[] args) {
        ApplicationContext context 
= 
            
new FileSystemXmlApplicationContext("beans-config.xml");
        IHello helloProxy 
=(IHello)context.getBean("helloProxy");
        helloProxy.hello(
"YYY");
    }
}
posted on 2006-07-28 17:07 knowhow 阅读(319) 评论(0)  编辑  收藏 所属分类: Framework

只有注册用户登录后才能发表评论。


网站导航: