Spring Boot提供的针对Servlet 3.0+容器的注册bean基类。该类的目的是用于向Servlet容器(Tomcat,Jetty等)注册工作组件,比如Servlet,Filter或者EventListener。
这是一个抽象基类,实现了接口ServletContextInitializer。ServletContextInitializer约定了当前RegistrationBean会在Servlet启动时被调用方法#onStartup。
该抽象基类提供了如下功能:
当前注册bean的优先级,通过属性order指定,缺省值为最低优先级Ordered.LOWEST_PRECEDENCE。当前注册bean是否被禁用,通过属性enabled指定。如果被禁用,Servlet容器启动时并不执行该注册bean的注册动作。缺省值为true。通过抽象方法的方式约定了实现子类必须实现某些功能,比如具体注册什么以及具体的注册逻辑都必须由子类实现提供。该类是一个抽象基类,主要目的是被子类继承和实现,具体有哪些子类可以参考上面的继承关系图。
源代码版本 : 2.1.3.RELEASE
package org.springframework.boot.web.servlet; import javax.servlet.ServletContext; import javax.servlet.ServletException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.core.Ordered; import org.springframework.util.StringUtils; public abstract class RegistrationBean implements ServletContextInitializer, Ordered { private static final Log logger = LogFactory.getLog(RegistrationBean.class); private int order = Ordered.LOWEST_PRECEDENCE; private boolean enabled = true; // ServletContextInitializer 接口约定的方法,会在 Servlet 容器启动时被调用, // 注意这里使用了 final 关键字,禁止子类覆盖 @Override public final void onStartup(ServletContext servletContext) throws ServletException { String description = getDescription(); if (!isEnabled()) { logger.info(StringUtils.capitalize(description) + " was not registered (disabled)"); return; } register(description, servletContext); } /** * Return a description of the registration. For example "Servlet resourceServlet" * @return a description of the registration */ protected abstract String getDescription(); /** * Register this bean with the servlet context. * 要求子类实现的主要方法 : 注册当前bean到指定 servlet 上下文 * @param description a description of the item being registered * @param servletContext the servlet context */ protected abstract void register(String description, ServletContext servletContext); /** * Flag to indicate that the registration is enabled. * @param enabled the enabled to set */ public void setEnabled(boolean enabled) { this.enabled = enabled; } /** * Return if the registration is enabled. * @return if enabled (default true) */ public boolean isEnabled() { return this.enabled; } /** * Set the order of the registration bean. * @param order the order */ public void setOrder(int order) { this.order = order; } /** * Get the order of the registration bean. * @return the order */ @Override public int getOrder() { return this.order; } }