首页投稿(暂停使用,暂停投稿)

Spring学习之路(六)

2017-07-20  本文已影响0人  秋灯锁忆

面向切面

package com.aop;
import java.lang.reflect.Method;
import org.springframework.aop.MethodBeforeAdvice;
//继承前置通知接口
public class MyMethodBeforeAdvice implements MethodBeforeAdvice {
    @Override
    //参数含义:被调用等方法名,方法传递的参数,目标对象
    public void before(Method arg0, Object[] arg1, Object arg2)
            throws Throwable {
        System.out.println("记录日志"+arg0.getName());
    }
}

配置代理:
先建立公共接口ParentInterface.java

package com.aop;
public interface ParentInterface {
    public void sayhello();
}

继承类Testone.java

package com.aop;
public class Testone implements ParentInterface {
    private String name;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @Override
    public void sayhello() {
        System.out.print("one hello"+name);
    }
}

beans.xml

<!-- 要写入注解对象 -->
<bean id="testone" class="com.aop.Testone">
    <property name="name" value="小红"></property>
</bean>
<!-- 前置通知对象 -->
<bean id="myMethodBeforeAdvice" class="com.aop.MyMethodBeforeAdvice" />
<!-- 代理对象 -->
<bean id="proxyFactoryBean" class="org.springframework.aop.framework.ProxyFactoryBean">
<!-- 引入接口,搭建桥梁 -->
    <property name="proxyInterfaces">
        <list>
            <value>com.aop.ParentInterface</value>
        </list>
    </property>
<!-- 引入通知 -->   
    <property name="interceptorNames">
        <list>
            <value>myMethodBeforeAdvice</value>
        </list>
    </property>
<!-- 目标对象-->    
    <property name="target" ref="testone" />
</bean>

测试代码Test.java

package com.aop;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test { 
    public static void main(String[] args) {
        ApplicationContext ac=new ClassPathXmlApplicationContext("com/aop/beans.xml");
        ParentInterface emp=(ParentInterface) ac.getBean("proxyFactoryBean");
//接口获取,该过程完成通知织入
        emp.sayhello();
//调用织入后的函数,完成目标
    }
}
上一篇下一篇

猜你喜欢

热点阅读