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

用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();

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/118768.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号