读书人

spring拦截器的一个容易例子

发布时间: 2012-10-30 16:13:36 作者: rapoo

spring拦截器的一个简单例子
转自:http://blog.csdn.net/yirentianran/article/details/3380529
今天在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" />
7. </property>
8. <property name="patterns">
9. <list>
10. <value>.*checkLogin.*</value>
11. </list>
12. </property>
13. </bean>
14.
15. <bean id="autoproxyaop"
16. 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的时候,若该类实现了接口,则返回其接口类型的实例,

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

读书人网 >编程

热点推荐