前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >用Spring提高java观察者模式灵活性

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

作者头像
全栈程序员站长
发布2022-07-12 16:35:09
1520
发布2022-07-12 16:35:09
举报

大家好,又见面了,我是全栈君,祝每个程序员都可以多学几门语言。

在上篇博客 用java观察者模式解耦经典三层架构 的最后,用了一个Client类把Listener的实现类注冊到了LoginEventSource类中,假设须要加入�新的逻辑,加入�新的listener类后,还是须要改动Client类,那么我们能够借助spring提供的容器来帮助我们完好观察者模式。

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

代码语言:javascript
复制
	<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代码则改为

代码语言:javascript
复制
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
		
		LoginEventSource loginEventSource=(LoginEventSource)ctx.getBean("loginEventSource");
		loginEventSource.notifyListenner();

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

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021年12月,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
容器服务
腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档