浅谈Spring事件监听

本文介绍了Spring的ApplicationContext接口及其功能,包括bean工厂、资源加载、事件发布和消息解析等。接着讨论了Spring的事件监听机制,涉及ApplicationEvent和ApplicationListener接口,以及如何通过实现ApplicationContextAware或ApplicationEventPublisherAware接口在普通bean中发布事件。文章通过示例代码展示了如何创建自定义事件和监听器,并演示了两种不同的事件发布方式。
声明:笔者以下所有的代码和实验都是基于Spring boot 的 2.0.0.RELEASE 版本。
           另外笔者能力有限,文中但凡有不对或者用词不当之处,望不吝指出。

在谈Spring的事件监听之前,让我们先了解一下Spring容器,什么是ApplicationContext ?
它是Spring的核心,Context我们通常解释为上下文环境,但是理解成容器会更好些。 
ApplicationContext则是应用的容器。
Spring把Bean(object)放在容器中,需要用就通过get方法取出来。

下面我们结合源码注视和ApplicationContext的类图来看看它到底提供给我们哪些能力
源码:
/*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.springframework.context;

import org.springframework.beans.factory.HierarchicalBeanFactory;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.core.env.EnvironmentCapable;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.lang.Nullable;

/**
* Central interface to provide configuration for an application.
* This is read-only while the application is running, but may be
* reloaded if the implementation supports this.
*
* <p>An ApplicationContext provides:
* <ul>
* <li>Bean factory methods for accessing application components.
* Inherited from {@link org.springframework.beans.factory.ListableBeanFactory}.
* <li>The ability to load file resources in a generic fashion.
* Inherited from the {@link org.springframework.core.io.ResourceLoader} interface.
* <li>The ability to publish events to registered listeners.
* Inherited from the {@link ApplicationEventPublisher} interface.
* <li>The ability to resolve messages, supporting internationalization.
* Inherited from the {@link MessageSource} interface.
* <li>Inheritance from a parent context. Definitions in a descendant context
* will always take priority. This means, for example, that a single parent
* context can be used by an entire web application, while each servlet has
* its own child context that is independent of that of any other servlet.
* </ul>
*
* <p>In addition to standard {@link org.springframework.beans.factory.BeanFactory}
* lifecycle capabilities, ApplicationContext implementations detect and invoke
* {@link ApplicationContextAware} beans as well as {@link ResourceLoaderAware},
* {@link ApplicationEventPublisherAware} and {@link MessageSourceAware} beans.
*
* @author Rod Johnson
* @author Juergen Hoeller
* @see ConfigurableApplicationContext
* @see org.springframework.beans.factory.BeanFactory
* @see org.springframework.core.io.ResourceLoader
*/
public interface ApplicationContext extends EnvironmentCapable, ListableBeanFactory, HierarchicalBeanFactory,
      MessageSource, ApplicationEventPublisher, ResourcePatternResolver {

   /**
    * Return the unique id of this application context.
    * @return the unique id of the context, or {@code null} if none
    */
   @Nullable
   String getId();

   /**
    * Return a name for the deployed application that this context belongs to.
    * @return a name for the deployed application, or the empty String by default
    */
   String getApplicationName();

   /**
    * Return a friendly name for this context.
    * @return a display name for this context (never {@code null})
    */
   String getDisplayName();

   /**
    * Return the timestamp when this context was first loaded.
    * @return the timestamp (ms) when this context was first loaded
    */
   long getStartupDate();

   /**
    * Return the parent context, or {@code null} if there is no parent
    * and this is the root of the context hierarchy.
    * @return the parent context, or {@code null} if there is no parent
    */
   @Nullable
   ApplicationContext getParent();

   /**
    * Expose AutowireCapableBeanFactory functionality for this context.
    * <p>This is not typically used by application code, except for the purpose of
    * initializing bean instances that live outside of the application context,
    * applying the Spring bean lifecycle (fully or partly) to them.
    * <p>Alternatively, the internal BeanFactory exposed by the
    * {@link ConfigurableApplicationContext} interface offers access to the
    * {@link AutowireCapableBeanFactory} interface too. The present method mainly
    * serves as a convenient, specific facility on the ApplicationContext interface.
    * <p><b>NOTE: As of 4.2, this method will consistently throw IllegalStateException
    * after the application context has been closed.</b> In current Spring Framework
    * versions, only refreshable application contexts behave that way; as of 4.2,
    * all application context implementations will be required to comply.
    * @return the AutowireCapableBeanFactory for this context
    * @throws IllegalStateException if the context does not support the
    * {@link AutowireCapableBeanFactory} interface, or does not hold an
    * autowire-capable bean factory yet (e.g. if {@code refresh()} has
    * never been called), or if the context has been closed already
    * @see ConfigurableApplicationContext#refresh()
    * @see ConfigurableApplicationContext#getBeanFactory()
    */
   AutowireCapableBeanFactory getAutowireCapableBeanFactory() throws IllegalStateException;

}

类图:

</
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值