spring 学习笔记 引入通知

创建引入

引入是为需要方法的类添加属性和方法。可以用一个已存在的类让他实现另外的接口,维持另外的状态(这也叫混合)。引入能够动态的建立复合对象,提供了多态继承的好处。

class AuditableIntroductionInterceptor extends DelegatingIntroductionInceptor{

     private Date lastModifiedDate ;
     public Date getLastModifiedDate(){}
     public void setLastModifiedDate(Date date){}
}
如果你的混合体要改变任何目标对象方法的行为的话,你就需要实现invoke()方法。
public Object invoke(MethodInvcation mi) throws Throwable{
     String name = mi.getMethod().getName();
     if(name.indexof("set") == 0){
            throw new IllegalModificationException();
     }
     return super.invoke(mi);
}
我们复写了invoke方法,所以他拦截所有的方法的调用。注意我们调用的super.invoke()而
不是mi.proceed().这样做是因为父类DelegatingIntroductionInterceptorkeyijiang可以
决定哪个类负责处理这个方法调用。这一点需要注意,当需要复写invoke方法时,你需要调用
super.invoke方法来确保调用正确的方法。

public class MyDDI extends DelegatingIntroductionInterceptor implements
		ModifyData {
	private static final long serialVersionUID = 8244858324942778490L;
	private String data;
	public void setData(String data) {
		this.data = data;
	}

	public String getData() {
		return this.data;
	}
}
public interface ModifyData {
	public void setData(String data);
	public String getData();
}
<bean id="myDII" class="study.spring.aop.advice.MyDDI"></bean>
	<!-- 默认的引入切入点通知(代理引入拦截器,对引入通知进行包装) -->
	<bean id="delegatingIntroductionInterceptor" class="org.springframework.aop.support.DelegatingIntroductionInterceptor">
		<constructor-arg ref="myDII"></constructor-arg>
	</bean>
	<!-- 目标对象 -->
	<bean id="welcomeServiceTarget" class="study.spring.aop.WelcomeServiceImpl"></bean>
	<!-- 对象代理 -->
	<bean id="welcomeService" class="org.springframework.aop.framework.ProxyFactoryBean">
		<!-- 代理接口集 -->
		<property name="proxyInterfaces">
			<list>
				<value>study.spring.aop.ModifyData</value>
			</list>		
		</property>
		<!-- 拦截器名集 -->
		<property name="interceptorNames">
			<list>
				<!-- <value>myMethodInterceptor</value> -->
				<value>delegatingIntroductionInterceptor</value>
			</list>
		</property>
		<!-- 指定目标对象 -->
		<property name="target" ref="welcomeServiceTarget"></property>
	</bean>
ApplicationContext ac = new ClassPathXmlApplicationContext("study/spring/aop/dii.xml");
		WelcomeService ws = (WelcomeService)ac.getBean("welcomeService");
		ModifyData md = (ModifyData)ws;
		md.setData("data");
		System.out.println(md.getData());


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值