`
zhaoshunxin
  • 浏览: 29075 次
  • 来自: 济南
社区版块
存档分类
最新评论

Spring 采用ObServer设计模式实现事件传递

 
阅读更多
Spring 采用ObServer设置模式实现事件传递
定义自己的事件
1、实现ApplicationListener 创建事件监听
public class EventListener implements ApplicationListener
{
    private String to;

    public void setTo(String to)
    {
        this.to = to;
    }

    public void onApplicationEvent(ApplicationEvent event)
    {
        if (event instanceof ObServerEvent)
        {
            ObServerEvent ev = (ObServerEvent) event;
            System.out.println(ev.getAdress() + " send mail to " + to);
        }
    }
}
实现 ApplicationContextAware 创建观察者
public class ObServer implements ApplicationContextAware
{
    String from;

    String message;

    public String getFrom()
    {
        return from;
    }

    public void setFrom(String from)
    {
        this.from = from;
    }
继承 ApplicationEvent 实现事件
public class ObServerEvent extends ApplicationEvent
{
    private String adress;

    private String text;

    public ObServerEvent(Object source, String address, String text)
    {
        super(source);
        this.adress = address;
        this.text = text;
    }

    public String getAdress()
    {
        return adress;
    }

    public String getText()
    {
        return text;
    }

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

}

    public String getMessage()
    {
        return message;
    }

    public void setMessage(String message)
    {
        this.message = message;
    }

    private ApplicationContext ctx;

    public void setApplicationContext(ApplicationContext ctx)
            throws BeansException
    {
        this.ctx = ctx;
    }

    public void sendMail()
    {
        ObServerEvent event = new ObServerEvent(this, from, message);
        ctx.publishEvent(event);
    }
}

applicationContext.xml
<bean id="obServer" class="observer.ObServer">
	<property name="from"><value>A</value>
	</property>
	<property name="message"><value>XXXXXX</value>
</bean>
<bean id="eventListener" class="observer.EventListener">
	<property name="to">
		<value>B</value>
	</property>
</bean>

测试
ObServer eventBean = (ObServer) context.getBean("obServer");
eventBean.sendMail();

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics