Spring Boot简化了Spring应用的开发,采用约定大于配置的思想,去繁从简,很方便就能构建一个独立的、产品级别的应用。html
开发笨重、配置繁多复杂、开发效率低下、部署流程复杂、第三方技术集成难度大。java
自动配置xxxAutoConfigurationreact
SpringBoot使用一个全局的配置文件。配置文件名是固定的。
-application.properties或者application.ymlweb
全局配置文件的做用是对一些默认配置进行修改spring
对比点 | @ConfigurationProperties | @Value |
---|---|---|
功能 | 批量注入配置文件中的属性 | 一个个指定 |
松散绑定(松散语法) | 支持 | 不支持 |
SpEL | 不支持 | 支持 |
JSR303数据校验 | 支持 | 不支持 |
复杂类型封装 | 支持 | 不支持 |
属性名匹配规则
-person.firstName 使用标准方式
-person.first-name 使用-
-person.first_name 使用_
-PERSON_FIRST_NAME 推荐系统属性使用这种写法json
@PropertySource
加载指定的配置文件浏览器
ConfigurationProperties
-与@Bean结合为属性赋值
-与@PropertySource(只能用于properties文件)结合读取指定文件。缓存
ConfigurationProperties Validation
-支持JSR303进行配置文件值校验。tomcat
@Component @PropertySource(value={"classpath:person.properties"}) @ConfigurationProperties(prefix="person") @Validated public class Person{ @Email @Value("${person.email}") private String email; }
RandomValuePropertySource
配置文件中可使用随机数
-${random.value}
-${random.int}
-${random.long}
-${random.int(10)}
-${random.int[1024,65536]}springboot
app.name=MyApp app.description=${app.name} is a SpringBoot Application
profile是Spring对不一样环境提供不一样配置功能的支持,能够经过激活指定参数的方式快速切换环境。
#### 1.多profile文件形式
格式:application-{profile}.properties/yml
application-dev.properties、application-prod.properties
spring.profiles.active=prod #激活指定配置 spring.profiles=prod server.port=80 # default表示未指定时的默认配置 spring.profiles=default server.port=8080
SpringBoot启动会扫描一下位置的application.properties或者application.yml文件做为SpringBoot的默认配置文件。
- file:./config/
- file:./
- classpath:/config/
-classpath:/
-以上是按照优先级从高到低的顺序,全部位置的文件都会被加载,高优先级配置内容会覆盖低优先级配置内容。
-能够经过配置spring.config.location来改变默认配置。
@Conditional扩展注解 | 做用(判断是否知足当期指定条件) |
---|---|
@ConditionalOnJava | 系统的java版本是否符合要求 |
@ConditionalOnBean | 容器中存在指定Bean |
@ConditionalOnMissingBean | 容器中不存在指定Bean |
@ConditionalOnExpression | 知足SpEL表达式指定 |
@ConditionalOnClass | 系统中有指定的类 |
@ConditionalOnMissingClass | 容器中没有指定类 |
@ConditionalOnSingleCandidate | 容器中只有一个指定的Bean,或者这个Bean是首选Bean |
@ConditionalOnProperty | 系统中指定的属性是否有指定的值 |
@ConditionalOnResource | 类路径下是否存在指定资源文件 |
@ConditionalOnWebApplication | 当前是web环境 |
@ConditionalOnNotWebApplication | 当前不是web环境 |
@ConditionalOnJndi | JNDI存在指定项 |
市场上存在很是多的日志框架,JUL(java.util.logging)、JCL(Apache Commons Logging)、Log4J、Log4J二、Logback、SLF4j、jboss-logging等。
日志门面 | 日志实现 |
---|---|
JCL、SLF4J、jboss-logging | log4j、JUL、Log4j二、Logback |
日志系统 | 配置文件 |
---|---|
Logback | logback-spring.xml、logback-spring.groovy、logback.xml或logback.groovy |
Log4j2 | log4j2-spring.xml、log4j2.xml |
JUL | logging.properties |
SpringBoot对SpringMVC的默认配置(WebMvcAutoConfiguration)以下:
- 支持静态资源,包括支持Wenjars - 静态首页访问 - 支持favicon.ico - 自动注册了Converter、GenericConverter、Formatter。 - Converter:转换器。 - Formatter:格式化器
编写一个配置类(@Configuration),是WebMvcConfigurerAdapter类型,不能标注@EnableWebMvc注解
@Configuration public class MyMvcConfig extends WebMvcConfigurerAdapter { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/desperado").setViewName("success"); } }
原理
若是想要使SpringMVC的自动配置失效,只须要在咱们自定义的配置类中添加@EnableWebMvc注解便可。
@EnableWebMvc @Configuration public class MyMvcConfig extends WebMvcConfigurerAdapter { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/desperado").setViewName("success"); } }
原理
@Import(DelegatingWebMvcConfiguation.class) public @interface EnableWebMvc{}
@Configuration public class DelegatingWebMvcConfiguation extend WebMvcConfigurationSupport{}
@Configuration @ConditionalOnWebApplication @ConditionalOnClass({Servlet.class,DispatcherServlet.class, WebMvcConfigurerAdapter.class}) //容器中没有这个组件,这个自动配置类才会生效 @ConditionalOnMissingBean(WebMvcConfigurationSupport.class) @AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10) @AutoConfigureAfter({DispatcherServletAutoConfiguration.class, ValidationAutoConfiguration.class}) public class WebMvcAutoConfiguration{}
使用自定义WebMvcConfigurationAdapter进行配置
//使用WebMvcConfigurationAdapter能够扩展SpringMVC的功能 @Configuration public class MyMvcConfig extends WebMvcConfigurerAdapter { @Override public void addViewControllers(ViewControllerRegistry registry) { //浏览器发送/desperado 请求来到success registry.addViewController("/desperado").setViewName("success"); } //全部的webMvcConfigurerAdapter组件都会一块儿起做用 @Bean //将组件注册到容器 public WebMvcConfigurerAdapter webMvcConfigurerAdapter(){ WebMvcConfigurerAdapter adapter = new WebMvcConfigurerAdapter() { @Override public void addViewControllers(ViewControllerRegistry registry) { //配置默认路径的页面 registry.addViewController("/").setViewName("login"); registry.addViewController("/index.html").setViewName("login"); } }; return adapter; } }
1.编写国际化配置文件
编写不一样语言的配置文件,好比login.properties、login_en_US.properties、login_zh_CN.properties等。
@EnableConfigurationProperties public class MessageSourceAutoConfiguration { private static final Resource[] NO_RESOURCES = new Resource[0]; public MessageSourceAutoConfiguration() { } @Bean @ConfigurationProperties( prefix = "spring.messages" ) public MessageSourceProperties messageSourceProperties() { return new MessageSourceProperties(); } @Bean public MessageSource messageSource(MessageSourceProperties properties) { ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); if (StringUtils.hasText(properties.getBasename())) { //设置国际化资源文件的基础名(去掉语言国家代码) messageSource.setBasenames(StringUtils.commaDelimitedListToStringArray(StringUtils.trimAllWhitespace(properties.getBasename()))); } if (properties.getEncoding() != null) { messageSource.setDefaultEncoding(properties.getEncoding().name()); } messageSource.setFallbackToSystemLocale(properties.isFallbackToSystemLocale()); Duration cacheDuration = properties.getCacheDuration(); if (cacheDuration != null) { messageSource.setCacheMillis(cacheDuration.toMillis()); } messageSource.setAlwaysUseMessageFormat(properties.isAlwaysUseMessageFormat()); messageSource.setUseCodeAsDefaultMessage(properties.isUseCodeAsDefaultMessage()); return messageSource; }
原理
根据请求头带来的区域信息获取Locale进行国际化。
原理
public class DefaultErrorAttributes implements ErrorAttributes { //获取错误页面的信息 public Map<String, Object> getErrorAttributes(ServerRequest request, boolean includeStackTrace) { Map<String, Object> errorAttributes = new LinkedHashMap(); errorAttributes.put("timestamp", new Date()); errorAttributes.put("path", request.path()); Throwable error = this.getError(request); HttpStatus errorStatus = this.determineHttpStatus(error); errorAttributes.put("status", errorStatus.value()); errorAttributes.put("error", errorStatus.getReasonPhrase()); errorAttributes.put("message", this.determineMessage(error)); this.handleException(errorAttributes, this.determineException(error), includeStackTrace); return errorAttributes; } }
@Controller @RequestMapping({"${server.error.path:${error.path:/error}}"}) public class BasicErrorController extends AbstractErrorController { //产生html类型的数据,浏览器发送的请求来打这个方法处理 @RequestMapping( produces = {"text/html"} ) public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) { HttpStatus status = this.getStatus(request); Map<String, Object> model = Collections.unmodifiableMap(this.getErrorAttributes(request, this.isIncludeStackTrace(request, MediaType.TEXT_HTML))); response.setStatus(status.value()); //去哪一个页面做为错误页面。包含页面地址和页面内容 ModelAndView modelAndView = this.resolveErrorView(request, response, status, model); return modelAndView != null ? modelAndView : new ModelAndView("error", model); } //产生json数据,其余客户端来到这个方法处理 @RequestMapping public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) { Map<String, Object> body = this.getErrorAttributes(request, this.isIncludeStackTrace(request, MediaType.ALL)); HttpStatus status = this.getStatus(request); return new ResponseEntity(body, status); } }
public class ErrorProperties { @Value("${error.path:/error}") private String path = "/error"; private boolean includeException; private ErrorProperties.IncludeStacktrace includeStacktrace; private final ErrorProperties.Whitelabel whitelabel; }
public class ErrorMvcAutoConfiguration { private static class StaticView implements View { private static final Log logger = LogFactory.getLog(ErrorMvcAutoConfiguration.StaticView.class); private StaticView() { } public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) throws Exception { if (response.isCommitted()) { String message = this.getMessage(model); logger.error(message); } else { StringBuilder builder = new StringBuilder(); Date timestamp = (Date)model.get("timestamp"); Object message = model.get("message"); Object trace = model.get("trace"); if (response.getContentType() == null) { response.setContentType(this.getContentType()); } builder.append("<html><body><h1>Whitelabel Error Page</h1>").append("<p>This application has no explicit mapping for /error, so you are seeing this as a fallback.</p>").append("<div id='created'>").append(timestamp).append("</div>").append("<div>There was an unexpected error (type=").append(this.htmlEscape(model.get("error"))).append(", status=").append(this.htmlEscape(model.get("status"))).append(").</div>"); if (message != null) { builder.append("<div>").append(this.htmlEscape(message)).append("</div>"); } if (trace != null) { builder.append("<div style='white-space:pre-wrap;'>").append(this.htmlEscape(trace)).append("</div>"); } builder.append("</body></html>"); response.getWriter().append(builder.toString()); } } private String htmlEscape(Object input) { return input != null ? HtmlUtils.htmlEscape(input.toString()) : null; } private String getMessage(Map<String, ?> model) { Object path = model.get("path"); String message = "Cannot render error page for request [" + path + "]"; if (model.get("message") != null) { message = message + " and exception [" + model.get("message") + "]"; } message = message + " as the response has already been committed."; message = message + " As a result, the response may have the wrong status code."; return message; } public String getContentType() { return "text/html"; } }
5.DefaultErrorViewResolver解析页面
public class DefaultErrorViewResolver implements ErrorViewResolver, Ordered { public ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status, Map<String, Object> model) { ModelAndView modelAndView = this.resolve(String.valueOf(status.value()), model); if (modelAndView == null && SERIES_VIEWS.containsKey(status.series())) { modelAndView = this.resolve((String)SERIES_VIEWS.get(status.series()), model); } return modelAndView; } private ModelAndView resolve(String viewName, Map<String, Object> model) { //默认去找一个页, error/404 String errorViewName = "error/" + viewName; //模板引擎能够解析这个页面地址就要模板引擎解析 TemplateAvailabilityProvider provider = this.templateAvailabilityProviders.getProvider(errorViewName, this.applicationContext); //模板引擎可用的状况下返回到errorViewName指定的视图地址 //模板引擎不能够,就在静态资源文件夹下找对应的页面 return provider != null ? new ModelAndView(errorViewName, model) : this.resolveResource(errorViewName, model); }
@ControllerAdvice public class MyExceptionHandler { @ResponseBody @ExceptionHandler(CustomException.class) public Map<String,Object> handleException(Exception e){ HashMap<String, Object> map = new HashMap<>(); map.put("code","错误信息"); map.put("message",e.getMessage()); return map; } }
2.转发到/error进行自适应响应效果处理。
@ControllerAdvice public class MyExceptionHandler { @ResponseBody @ExceptionHandler(CustomException.class) public String handleException(Exception e, HttpServletRequest request){ HashMap<String, Object> map = new HashMap<>(); //传入咱们本身的错误状态码,不然就不会进入定制错误页面的解析流程 request.setAttribute("java.servlet.error.status_code","500"); map.put("code","错误信息"); map.put("message",e.getMessage()); //转发到/error return "forward:/error"; } }
出现错误以后,回来到/error请求,会被BasicErrorController处理,响应出去能够获取的数据是由getErrorAttributes获得的。
//给容器中加入自定义的ErrorAttributes @Component public class MyErrorAttributes extends DefaultErrorAttributes { @Override public Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) { //获取ErrorAttributes的map Map<String, Object> map = super.getErrorAttributes(webRequest, includeStackTrace); //加入本身属性字段 map.put("name","desperado"); return map; } }
SpringBoot默认使用Tomcat做为内嵌的Servlet容器
在配置文件application文件中修改和server有关的配置。
server.port=8081 server.context_path=/crud server.tomcat.uri-encoding=utf-8
编写一个EmbeddedServletContainerCustomizer(2.x中使用WebServerFactoryCustomizer),来修改Servlet容器的配置。
@Bean public WebServerFactoryCustomizer<ConfigurableWebServerFactory> webServerFactoryCustomizer(){ return new WebServerFactoryCustomizer<ConfigurableWebServerFactory>(){ @Override public void customize(ConfigurableWebServerFactory factory) { factory.setPort(8081); } }; }
因为SpringBoot是默认以jar包的方式启动内嵌的Servlet容器来启动SpringBoot的web应用,没有web.xml文件。因此注册Servlet、Filter、Listener的方式也不一样
@Bean public ServletRegistrationBean<MyServlet> myServlet(){ ServletRegistrationBean<MyServlet> registrationBean = new ServletRegistrationBean<>(new MyServlet(), "/myServlet"); return registrationBean; }
@Bean public FilterRegistrationBean<MyFilter> myFilter(){ FilterRegistrationBean<MyFilter> registrationBean = new FilterRegistrationBean<>(); registrationBean.setFilter(new MyFilter()); registrationBean.setUrlPatterns(Arrays.asList("/hello","/myServlet")); return registrationBean; }
@Bean public ServletListenerRegistrationBean<MyListener> myListener(){ ServletListenerRegistrationBean<MyListener> registrationBean = new ServletListenerRegistrationBean<>(new MyListener()); return registrationBean; }
替换为其余的Servlet很是简单,只须要在pom中引入其依赖,而后排除tomcat的依赖便可.
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jetty</artifactId> </dependency>
@Configuration class ServletWebServerFactoryConfiguration { ServletWebServerFactoryConfiguration() { } @Configuration @ConditionalOnClass({Servlet.class, Undertow.class, SslClientAuthMode.class}) @ConditionalOnMissingBean( value = {ServletWebServerFactory.class}, search = SearchStrategy.CURRENT ) public static class EmbeddedUndertow { public EmbeddedUndertow() { } @Bean public UndertowServletWebServerFactory undertowServletWebServerFactory() { return new UndertowServletWebServerFactory(); } } @Configuration @ConditionalOnClass({Servlet.class, Server.class, Loader.class, WebAppContext.class}) @ConditionalOnMissingBean( value = {ServletWebServerFactory.class}, search = SearchStrategy.CURRENT ) public static class EmbeddedJetty { public EmbeddedJetty() { } @Bean public JettyServletWebServerFactory JettyServletWebServerFactory() { return new JettyServletWebServerFactory(); } } @Configuration //判断当前是否引入了tomcat依赖 @ConditionalOnClass({Servlet.class, Tomcat.class, UpgradeProtocol.class}) ///判断当前容器没有用户本身定义ServletWebServerFactory: //嵌入式的Servlet容器工厂;做用:建立嵌入式的Servlet容器 @ConditionalOnMissingBean( value = {ServletWebServerFactory.class}, search = SearchStrategy.CURRENT ) public static class EmbeddedTomcat { public EmbeddedTomcat() { } @Bean public TomcatServletWebServerFactory tomcatServletWebServerFactory() { return new TomcatServletWebServerFactory(); } } }
4.以tomcat为例
public WebServer getWebServer(ServletContextInitializer... initializers) { Tomcat tomcat = new Tomcat(); File baseDir = this.baseDirectory != null ? this.baseDirectory : this.createTempDir("tomcat"); tomcat.setBaseDir(baseDir.getAbsolutePath()); Connector connector = new Connector(this.protocol); tomcat.getService().addConnector(connector); this.customizeConnector(connector); tomcat.setConnector(connector); tomcat.getHost().setAutoDeploy(false); this.configureEngine(tomcat.getEngine()); Iterator var5 = this.additionalTomcatConnectors.iterator(); while(var5.hasNext()) { Connector additionalConnector = (Connector)var5.next(); tomcat.getService().addConnector(additionalConnector); } this.prepareContext(tomcat.getHost(), initializers); return thisb.getTomcatWebServer(tomcat); }
public class WebServerFactoryCustomizerBeanPostProcessor implements BeanPostProcessor, BeanFactoryAware { //初始化以前 public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { //若是当前初始化的是一个WebServerFactory类型的组件 if (bean instanceof WebServerFactory) { this.postProcessBeforeInitialization((WebServerFactory)bean); } return bean; } public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { return bean; } private void postProcessBeforeInitialization(WebServerFactory webServerFactory) { // 获取全部的定制器,调用每个定制器的customize方法来给servlet容器进行属性赋值 ((Callbacks)LambdaSafe.callbacks(WebServerFactoryCustomizer.class, this.getCustomizers(), webServerFactory, new Object[0]).withLogger(WebServerFactoryCustomizerBeanPostProcessor.class)).invoke((customizer) -> { customizer.customize(webServerFactory); }); } private Collection<WebServerFactoryCustomizer<?>> getCustomizers() { if (this.customizers == null) { // 定制Servlet容器,给容器中能够添加一个WebServerFactoryCustomizer类型的组件 this.customizers = new ArrayList(this.getWebServerFactoryCustomizerBeans()); this.customizers.sort(AnnotationAwareOrderComparator.INSTANCE); this.customizers = Collections.unmodifiableList(this.customizers); } return this.customizers; } private Collection<WebServerFactoryCustomizer<?>> getWebServerFactoryCustomizerBeans() { //从容器中获取全部这个类型的组件:WebServerFactoryCustomizer return this.beanFactory.getBeansOfType(WebServerFactoryCustomizer.class, false, false).values(); } }
总结
protected ConfigurableApplicationContext createApplicationContext() { Class<?> contextClass = this.applicationContextClass; if (contextClass == null) { try { switch(this.webApplicationType) { case SERVLET: contextClass = Class.forName("org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext"); break; case REACTIVE: contextClass = Class.forName("org.springframework.boot.web.reactive.context.AnnotationConfigReactiveWebServerApplicationContext"); break; default: contextClass = Class.forName("org.springframework.context.annotation.AnnotationConfigApplicationContext"); } } catch (ClassNotFoundException var3) { throw new IllegalStateException("Unable create a default ApplicationContext, please specify an ApplicationContextClass", var3); } } return (ConfigurableApplicationContext)BeanUtils.instantiateClass(contextClass); }
public void refresh() throws BeansException, IllegalStateException { Object var1 = this.startupShutdownMonitor; synchronized(this.startupShutdownMonitor) { //准备刷新的context this.prepareRefresh(); //调用子类去刷新内部的实例工厂 ConfigurableListableBeanFactory beanFactory = this.obtainFreshBeanFactory(); //准备在这个context中要使用的实例工厂 this.prepareBeanFactory(beanFactory); try { // 容许在上下文子类中对bean工厂进行后置处理。 this.postProcessBeanFactory(beanFactory); //在context中调用注册为bean的工厂处理器。 this.invokeBeanFactoryPostProcessors(beanFactory); //注册拦截bean建立的bean处理器。 this.registerBeanPostProcessors(beanFactory); //初始化此context的消息源 this.initMessageSource(); //初始化此上下文的事件多播器。 this.initApplicationEventMulticaster(); //在特定的context子类中初始化其余特殊bean。 this.onRefresh(); // 检查监听器bean并注册它们。 this.registerListeners(); // 实例化全部剩余(非延迟初始化)单例。 this.finishBeanFactoryInitialization(beanFactory); //最后一步:发布相应的事件。 this.finishRefresh(); } catch (BeansException var9) { if (this.logger.isWarnEnabled()) { this.logger.warn("Exception encountered during context initialization - cancelling refresh attempt: " + var9); } //摧毁已经建立的单例以免占用资源。 this.destroyBeans(); //重置 ‘active’ 标志 this.cancelRefresh(var9); //Propagate exception to caller. throw var9; } finally { //从咱们开始,重置Spring核心中的常见内省缓存 //可能再也不须要单例bean的元数据了... this.resetCommonCaches(); } } }
private void createWebServer() { WebServer webServer = this.webServer; ServletContext servletContext = this.getServletContext(); if (webServer == null && servletContext == null) { ServletWebServerFactory factory = this.getWebServerFactory(); this.webServer = factory.getWebServer(new ServletContextInitializer[]{this.getSelfInitializer()}); } else if (servletContext != null) { try { this.getSelfInitializer().onStartup(servletContext); } catch (ServletException var4) { throw new ApplicationContextException("Cannot initialize servlet context", var4); } } this.initPropertySources(); }
获取嵌入式的Servlet容器工厂: ServletWebServerFactory factory = this.getWebServerFactory();从IOC容器中获取ServletWebServerFactory组件;
使用容器工厂获取嵌入式的Servlet容器:his.webServer = factory.getWebServer(new ServletContextInitializer[]{this.getSelfInitializer()});
public WebServer getWebServer(ServletContextInitializer... initializers) { Tomcat tomcat = new Tomcat(); File baseDir = this.baseDirectory != null ? this.baseDirectory : this.createTempDir("tomcat"); tomcat.setBaseDir(baseDir.getAbsolutePath()); Connector connector = new Connector(this.protocol); tomcat.getService().addConnector(connector); this.customizeConnector(connector); tomcat.setConnector(connector); tomcat.getHost().setAutoDeploy(false); this.configureEngine(tomcat.getEngine()); Iterator var5 = this.additionalTomcatConnectors.iterator(); while(var5.hasNext()) { Connector additionalConnector = (Connector)var5.next(); tomcat.getService().addConnector(additionalConnector); } this.prepareContext(tomcat.getHost(), initializers); return this.getTomcatWebServer(tomcat); }
9.先启动嵌入式的Servlet容器,再将IOC容器中剩余的没有建立出来的对象获取出来、IOC容器启动就会建立嵌入式的Servlet容器。
优势:简单、便捷。
缺点:默认不支持JSP,优化定制比较复杂。
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring‐boot‐starter‐tomcat</artifactId> <scope>provided</scope> </dependency>
public class ServletInitializer extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { //传入SpringBoot应用的主程序 return application.sources(SpringBoot04WebJspApplication.class); } }
原理
启动服务器,服务器启动SpringBoot应用[SpringBootServletInitializer],启动IOC容器。
规则
@HandlesTypes({WebApplicationInitializer.class}) public class SpringServletContainerInitializer implements ServletContainerInitializer { public SpringServletContainerInitializer() { } public void onStartup(@Nullable Set<Class<?>> webAppInitializerClasses, ServletContext servletContext) throws ServletException { List<WebApplicationInitializer> initializers = new LinkedList(); Iterator var4; if (webAppInitializerClasses != null) { var4 = webAppInitializerClasses.iterator(); while(var4.hasNext()) { Class<?> waiClass = (Class)var4.next(); if (!waiClass.isInterface() && !Modifier.isAbstract(waiClass.getModifiers()) && WebApplicationInitializer.class.isAssignableFrom(waiClass)) { try { initializers.add((WebApplicationInitializer)ReflectionUtils.accessibleConstructor(waiClass, new Class[0]).newInstance()); } catch (Throwable var7) { throw new ServletException("Failed to instantiate WebApplicationInitializer class", var7); } } } } if (initializers.isEmpty()) { servletContext.log("No Spring WebApplicationInitializer types detected on classpath"); } else { servletContext.log(initializers.size() + " Spring WebApplicationInitializers detected on classpath"); AnnotationAwareOrderComparator.sort(initializers); var4 = initializers.iterator(); while(var4.hasNext()) { WebApplicationInitializer initializer = (WebApplicationInitializer)var4.next(); initializer.onStartup(servletContext); } } } }
至关于SpringBootServletInitializer的类会被建立对象,并执行onStartup()方法。
SpringBootServletInitializer实例执行onStartup的时候会crateRootApplicationContext建立容器。
protected WebApplicationContext createRootApplicationContext(ServletContext servletContext) { // 1.建立SpringApplicationBuilder SpringApplicationBuilder builder = this.createSpringApplicationBuilder(); builder.main(this.getClass()); ApplicationContext parent = this.getExistingRootWebApplicationContext(servletContext); if (parent != null) { this.logger.info("Root context already created (using as parent)."); servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, (Object)null); builder.initializers(new ApplicationContextInitializer[]{new ParentContextApplicationContextInitializer(parent)}); } builder.initializers(new ApplicationContextInitializer[]{new ServletContextApplicationContextInitializer(servletContext)}); builder.contextClass(AnnotationConfigServletWebServerApplicationContext.class); // 2.调用configure方法,子类从新了这个方法,将SpringBoot的主程序类传入 builder = this.configure(builder); builder.listeners(new ApplicationListener[]{new SpringBootServletInitializer.WebEnvironmentPropertySourceInitializer(servletContext)}); // 3.使用builder建立一个Spring应用 SpringApplication application = builder.build(); if (application.getAllSources().isEmpty() && AnnotationUtils.findAnnotation(this.getClass(), Configuration.class) != null) { application.addPrimarySources(Collections.singleton(this.getClass())); } Assert.state(!application.getAllSources().isEmpty(), "No SpringApplication sources have been defined. Either override the configure method or add an @Configuration annotation"); //确保错误页被注册 if (this.registerErrorPageFilter) { application.addPrimarySources(Collections.singleton(ErrorPageFilterConfiguration.class)); } // 4. q启动Spring应用 return this.run(application); }
Spring的应用启动而且建立IOC容器。
先启动Servlet容器,再启动SpringBoot应用。