Sping框架两个重要思想是IOC和AOP,AOP全名是aspect oriented programming,即面向切面编程的意思。AOP思想允许我们在执行业务代码的前后执行另外的代码,如写日志、验证权限。其实Servlet中的Filter就体现了AOP思想。
Spring中,AOP需要继承特定的接口。这些实现了AOP接口的类被称为Interceptor(拦截器),Interceptor有多种,有方法前拦截器、方法后拦截器、around拦截器、异常拦截器。
下面是一个方法前拦截器:
MethodBeforeAdviceImpl.java:
package com.yeetrack.mavenSpring;
import java.lang.reflect.Method;
import java.util.Arrays;
import org.springframework.aop.MethodBeforeAdvice;
public class MethodBeforeAdviceImpl implements MethodBeforeAdvice
{
public void before(Method arg0, Object[] arg1, Object arg2)
throws Throwable
{
// TODO Auto-generated method stub
System.out.println("这是插入进来的方法,方法调用前执行---");
System.out.println("Method: "+ arg0.getName()); //输出方法名字
System.out.println("Args: " + Arrays.asList(arg1)); //输出方法参数列表
System.out.println("Object: "+arg2); //输出对象
}
}
当我们在applicationContext.xml为某个类的方法A定义了此拦截器后,spring在执行方法A之前会调用MethodBeforeAdviceImpl类中的before方法,参数分别为方法A的方法名、参数列表和A所在的类实例。
在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"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"
default-autowire="byName">
<!-- 拦截器对象 -->
<bean id="methodBeforeAdviceImpl" class="com.yeetrack.mavenSpring.MethodBeforeAdviceImpl"></bean>
<!-- 拦截器配置 -->
<bean id="theAdvisor" class="org.springframework.aop.support.NameMatchMethodPointcutAdvisor">
<!-- 拦截器属性设置 -->
<property name="advice">
<ref local="methodBeforeAdviceImpl"/>
</property>
<!-- 拦截所有方法 -->
<property name="mappedName" value="*"></property>
</bean>
<!-- DAO对象 -->
<bean id="daoImpl" class="com.yeetrack.mavenSpring.DaoImpl"></bean>
<!-- Service对象 -->
<bean id="serviceImpl" class="com.yeetrack.mavenSpring.ServiceImpl">
<!-- 设置dao属性 -->
<property name="dao" ref="daoImpl"></property>
</bean>
<!-- Spring代理类 -->
<bean id="service" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="interceptorNames" value="theAdvisor"></property><!-- 拦截器设置 -->
<property name="target"> <!-- 被拦截的对象 -->
<ref local="serviceImpl"/>
</property>
</bean>
</beans>
配置完之后,不用修改我们的SpringTest.java的代码,再次运行SpringTest可以看到首先执行了拦截器中的before方法,运行结果:
这是插入进来的方法,方法调用前执行---
```html
Method: sayHello
Args: [Good Day!]
Object: com.yeetrack.mavenSpring.ServiceImpl@67eb366
Hello, Good Day!
java Spring框架IOC(控制反转)
java Spring框架AOP(面向切面编程)
版权声明
本站文章、图片、视频等(除转载外),均采用知识共享署名 4.0 国际许可协议(CC BY-NC-SA 4.0),转载请注明出处、非商业性使用、并且以相同协议共享。
© 空空博客,本文链接:https://www.yeetrack.com/?p=13
近期评论