spring拦截器的一个简单例子

转自:[url]http://blog.csdn.net/yirentianran/article/details/3380529[/url]
今天在SSH中用到spring拦截器,所以先在一个只有spring的测试项目中写了一个拦截器的一个简单例子,

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

Purview接口.

1. package aop;
2.
3. public interface Purview {
4. void checkLogin();
5. }

PurviesImpl类,Purview接口的实现类.

1. package aop;
2.
3. public class PurviewImpl implements Purview {
4.
5. public void checkLogin() {
6. System.out.println("This is checkLogin method!");
7. }
8. }
9.

PurviewAdvice类,拦截器类.

1. package aop;
2.
3. import java.lang.reflect.Method;
4. import org.springframework.aop.MethodBeforeAdvice;
5.
6. public class PurviewAdvice implements MethodBeforeAdvice {
7. public void before(Method arg0, Object[] arg1, Object arg2)
8. throws Throwable {
9. System.out.println("This is before method!");
10. }
11. }
12.

Test类,测试类.

1. package aop;
2.
3. import org.springframework.context.ApplicationContext;
4. import org.springframework.context.support.ClassPathXmlApplicationContext;
5.
6. public class Test {
7. public static void main(String[] args) {
8. // TODO 自动生成方法存根
9. ApplicationContext ctx = new ClassPathXmlApplicationContext(
10. "applicationContext.xml");
11. PurviewImpl purviewImpl = (PurviewImpl) ctx.getBean("purviewImpl");
12. purviewImpl.checkLogin();
13.
14. }
15.
16. }
17.

applicationContext.xml配置文件.

1. <bean id="purviewImpl" class="aop.PurviewImpl"></bean>
2. <bean id="purviewAdvice" class="aop.PurviewAdvice"></bean>
3. <bean id="purviewAdvisor"
4. class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
5. <property name="advice">
6. <ref local="purviewAdvice" />
7. </property>
8. <property name="patterns">
9. <list>
10. <value>.*checkLogin.*</value>
11. </list>
12. </property>
13. </bean>
14.
15. <bean id="autoproxyaop"
16. class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
17. <property name="beanNames">
18. <value>purviewImpl</value>
19. </property>
20. <property name="interceptorNames">
21. <list>
22. <value>purviewAdvisor</value>
23. </list>
24. </property>
25. </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的时候,若该类实现了接口,则返回其接口类型的实例,

若直接返回该实现类类型的实例则会报错,错误信息如上所述.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值