依赖注入就不不多讲直接见程序体现,主要说说面向切面的编程(AOP)
首当其冲的自然是创建一个典型的spring切面
- 创建通知,通常Spring有5种形式的通知:Before,After-returning ,After-throwing,Around,Introduction
- 定义切点和通知者:正则表达式切点and联合切点与通知者
其次就是创建代理了,通常采用ProxyFactoryBean,当然还有自动代理
ApplicationContext.xml(spring的关键配置文件)如下:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <bean id="music" class="entertainment.PopMusic"></bean> <bean id="singerTarget" class="entertainment.PopSinger"> <property name="name" value="Michael Jackson"></property> <property name="song" ref="music"></property> </bean> <bean id="listener" class="entertainment.Listener"/> <bean id="listenerAdvice" class="entertainment.ListenerAdvice"> <property name="listener" ref="listener"/> </bean> <!--定义切点和通知者--> <bean id="listenAdvisor" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor"> <property name="advice" ref="listenerAdvice"/> <property name="pattern" value=".*sing"/> </bean> <!--设置代理--> <bean id="audienceProxyBase" class="org.springframework.aop.framework.ProxyFactoryBean" abstract="true"> <property name="proxyInterfaces" value="entertainment.Singer"/> <property name="interceptorNames" value="listenAdvisor"/> </bean> <bean id="singer" parent="audienceProxyBase"> <property name="target" ref="singerTarget"/> </bean> </beans>
来看看这几个关键的bean:
- singerTarget,对应了PopSinger类(实现了Singer接口),property(name)调用setName()方法,property(song)调用setSong()方法,其中song指定到music Bean
- listenAdvisor Bean定义了一个具有正则表达式切点的通知者,RegexpMethodPointcutAdvisor是个特殊的通知者类,可以在一个Bean里定义切点和通知者。
- Singer Bean是扩展自audienceProxyBase Bean,
- Singer Bean的第一个属性告诉ProxyFactoryBean哪个是Bean的代理,interceptorNames则告诉ProxyFactoryBean哪个通知者要应用于被代理的Bean
- proxyInterfaces属性告诉ProxyFactoryBean代理应该实现哪个接口
通知者类:
package entertainment;
import java.lang.reflect.Method;
import org.springframework.aop.AfterReturningAdvice;
import org.springframework.aop.MethodBeforeAdvice;
/*
* 创建通知
*/
public class ListenerAdvice implements MethodBeforeAdvice,AfterReturningAdvice{
private Listener listener;
public void before(Method arg0, Object[] arg1, Object arg2) throws Throwable {
listener.takeSeat();
}
public void afterReturning(Object arg0, Method arg1, Object[] arg2, Object arg3) throws Throwable {
listener.applaud();
}
public void setListener(Listener listener){
this.listener=listener;
}
}