今天在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的时候,若该类实现了接口,则返回其接口类型的实例,
若直接返回该实现类类型的实例则会报错,错误信息如上所述.