spring拦截器的简单例子

先定义一个接口:

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.....

 

你可能感兴趣的:(spring)