spring拦截器的一个简单例子

来源:互联网 发布:pca分析软件 编辑:程序博客网 时间:2024/06/14 14:42

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

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

Purview接口.

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

PurviesImpl类,Purview接口的实现类.

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

PurviewAdvice类,拦截器类.

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

Test类,测试类.

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

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.     <bean id="autoproxyaop"
  15.         class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
  16.         <property name="beanNames">
  17.             <value>purviewImpl</value>
  18.         </property>
  19.         <property name="interceptorNames">
  20.             <list>
  21.                 <value>purviewAdvisor</value>
  22.             </list>
  23.         </property>
  24.     </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的时候,若该类实现了接口,则返回其接口类型的实例,

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