spring拦截器

今天在SSH中用到spring拦截器,所以先在一个只有spring的测试项目中写了一个拦截器的一个简单例子,

结果还遇到了一点小错误,一下就按时间发展顺序记述.

Purview接口.

package aop;

public interface Purview {
    void checkLogin();
}
PurviesImpl类,Purview接口的实现类.

package aop;

public class PurviewImpl implements Purview {

    public void checkLogin() {
        System.out.println("This is checkLogin method!");
    }
}

PurviewAdvice类,拦截器类.

package aop;

import java.lang.reflect.Method;
import org.springframework.aop.MethodBeforeAdvice;

public class PurviewAdvice implements MethodBeforeAdvice {
    public void before(Method arg0, Object[] arg1, Object arg2)
            throws Throwable {
        System.out.println("This is before method!");
    }
}

Test类,测试类.

package aop;

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

public class Test {
    public static void main(String[] args) {
        // TODO 自动生成方法存根
        ApplicationContext ctx = new ClassPathXmlApplicationContext(
                "applicationContext.xml");
        PurviewImpl purviewImpl = (PurviewImpl) ctx.getBean("purviewImpl");
        purviewImpl.checkLogin();

    }

}

applicationContext.xml配置文件.

    <bean id="purviewImpl" class="aop.PurviewImpl"></bean>
    <bean id="purviewAdvice" class="aop.PurviewAdvice"></bean>
    <bean id="purviewAdvisor"
        class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
        <property name="advice">
            <ref local="purviewAdvice" />
        </property>
        <property name="patterns">
            <list>
                <value>.*checkLogin.*</value>
            </list>
        </property>
    </bean>

    <bean id="autoproxyaop"
        class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
        <property name="beanNames">
            <value>purviewImpl</value>
        </property>
        <property name="interceptorNames">
            <list>
                <value>purviewAdvisor</value>
            </list>
        </property>
    </bean>
运行结果报错,错误信息为:

Exception in thread "main" java.lang.ClassCastException: $Proxy1
 at aop.Test.main(Test.java:34)

将Test类中

PurviewImpl purviewImpl = (PurviewImpl) ctx.getBean("purviewImpl");

修改为

Purview purviewImpl = (Purview) ctx.getBean("purviewImpl");

程序运行结果为:

This is before method!
This is checkLogin method!

至此拦截器使用成功!

总结:用spring得到bean的时候,若该类实现了接口,则返回其接口类型的实例,

若直接返回该实现类类型的实例则会报错,错误信息如上所述.

 

本文来自优快云博客,转载请标明出处:http://blog.youkuaiyun.com/yirentianran/archive/2008/11/26/3380529.aspx

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值