spring拦截器的简单例子

本文介绍了如何使用Spring框架的AOP(面向切面编程)特性,通过创建自定义的前置通知类,在目标方法执行前进行特定的处理,实现了代理与拦截的功能。详细阐述了接口定义、实现类、前置通知类的编写以及在配置文件中的整合过程,并通过测试类验证了整个流程的正确性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

先定义一个接口:

package com.chinasoft.pur;

public interface Purview {
	public void logincheck();

}

 实现类:

package com.chinasoft.pur;

public class PurviewImpl implements Purview{

	public void logincheck() {
		System.out.println("login.....");
		
	}
}

 拦截logincheck之前具体要处理的:

package com.chinasoft.pur;

import java.lang.reflect.Method;

import org.springframework.aop.MethodBeforeAdvice;

public class BeforeMethod implements MethodBeforeAdvice{
 
    public void before(Method arg0, Object[] arg1, Object arg2)throws Throwable {
             System.out.println("befor login...");
    	
    }
}

 在applicationContext.xml配置:

<?xml version="1.0" encoding="UTF-8"?>
<beans
	xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<bean id="purviewimpl" class="com.chinasoft.pur.PurviewImpl"></bean>

<bean id="beforem" class="com.chinasoft.pur.BeforeMethod"></bean>

<bean id="puradvice" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
	<property name="advice">
	<ref bean="beforem"/>
	</property>
	<property name="pattern">
	<value>.*logincheck*.</value>
	</property>
</bean>

<bean id="autoproxy" class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
   <property name="beanNames">
      <value>purviewimpl</value>
   </property>
   <property name="interceptorNames">
     <value>puradvice</value>
   </property>
</bean>


</beans>

 测试类:

 

package com.chinasoft.pur;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
		Purview pur= (Purview) context.getBean("purviewimpl");
		pur.logincheck();

	}
}

 输出结果:

befor login...
login.....

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值