spring拦截器的一个简单例子
来源:互联网 发布:pca分析软件 编辑:程序博客网 时间:2024/06/14 14:42
今天在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的时候,若该类实现了接口,则返回其接口类型的实例,
若直接返回该实现类类型的实例则会报错,错误信息如上所述.
- spring拦截器的一个简单例子
- spring拦截器的一个简单例子
- 拦截器概述及其简单实现的一个例子
- spring mvc 拦截器简单例子
- spring 拦截器例子
- spring 拦截器例子
- Spring 拦截器的使用 例子
- spring-mvc 的 拦截器应用例子
- 使用拦截器的简单例子
- struts拦截器的使用(简单例子)
- 一个Spring简单例子
- 一个简单的Spring实现的例子
- 一个简单的Spring的AOP例子
- 一个简单的Spring的AOP例子
- 一个简单的Spring的AOP例子
- 一个简单的Spring的AOP例子
- 一个简单的Spring的AOP例子
- 一个简单的Spring的AOP例子
- ComboBox为何不显示下拉框?
- 去掉非聚焦 stringGrid 的最后选中的 cell 颜色
- 61条面向对象设计的经验原则,不错~
- Windows Server 2008 新功能
- DataGridTextBoxColumnTrim:DataGrid不能完全显示时显示,部分显示“...”
- spring拦截器的一个简单例子
- Win32汇编教程五:菜单和加速键的使用
- httpModules
- C语言之typedef的问题
- 关于在Windows server 2008下安装应用程序的解决方案
- class和struct做类型定义时的区别
- 新手哦
- 汇编工具下载
- 体验windows server2008服务器操作系统