zoukankan      html  css  js  c++  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();



  • 相关阅读:
    lnmp分离及其迁移数之一---数据库迁移
    lnmp wordpress...
    LNMP安装
    rpm 强制卸载
    ss ifconfig工具
    nginx--日志
    nginx--模块2--基于用户
    python-网络编程
    基本数据之-字典
    Python【day 9】函数入门1
  • 原文地址:https://www.cnblogs.com/yxwkf/p/3893324.html
Copyright © 2011-2022 走看看