初识spring依赖注入和AOP
?依赖注入就不不多讲直接见程序体现,主要说说面向切面的编程(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" value="Michael Jackson"></property><property name="song" ref="music"></property></bean><bean id="listener" ref="listener"/></bean><!--定义切点和通知者--><bean id="listenAdvisor" ref="listenerAdvice"/><property name="pattern" value=".*sing"/></bean><!--设置代理--><bean id="audienceProxyBase"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 BeanlistenAdvisor Bean定义了一个具有正则表达式切点的通知者,RegexpMethodPointcutAdvisor是个特殊的通知者类,可以在一个Bean里定义切点和通知者。Singer Bean是扩展自audienceProxyBase Bean,Singer Bean的第一个属性告诉ProxyFactoryBean哪个是Bean的代理,interceptorNames则告诉ProxyFactoryBean哪个通知者要应用于被代理的BeanproxyInterfaces属性告诉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;}}