用Spring提高java观察者模式灵活性

在上篇博客 用java观察者模式解耦经典三层架构 的最后,用了一个Client类把Listener的实现类注册到了LoginEventSource类中,如果需要添加新的逻辑,添加新的listener类后,还是需要修改Client类,那么我们可以借助spring提供的容器来帮助我们完善观察者模式。


在spring,在src下建立spring配置文件


	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">

		<property name="configLocation" value="classpath:hibernate.cfg.xml"></property>

	</bean>
	<!-- EventSource -->
	<bean id="loginEventSource" class="com.tgb.chargeSystem.LoginEventSource">
	</bean>
	
	<!-- Listener -->
	<bean id="loginLogListener" class="com.tgb.chargeSystem.LoginLogListener">
	</bean>
	<bean id="loginVerificationListener" class="com.tgb.chargeSystem.LoginVerificationListener">
	</bean>
	
	
	<bean id="registerLoginVerificationListener" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
		<property name="targetObject">
			<ref local="loginEventSource" />
		</property>
		<property name="targetMethod">
			<value>registerListener</value>
		</property>
		<property name="arguments">
			<list>
				<ref bean="loginVerificationListener" />
			</list>
		</property>
	</bean>
	
	<bean id="registerLoginLogListener" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
		<property name="targetObject">
			<ref local="loginEventSource" />
		</property>
		<property name="targetMethod">
			<value>registerListener</value>
		</property>
		<property name="arguments">
			<list>
				<ref bean="loginLogListener" />
			</list>
		</property>
	</bean>
通过MethodInvokingFactoryBean,我们可以通过配置文件把Listener注册到对应的事件源,因此避免了在类中的硬编码。

而client代码则改为

ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
		
		LoginEventSource loginEventSource=(LoginEventSource)ctx.getBean("loginEventSource");
		loginEventSource.notifyListenner();



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 9
    评论
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值