Spring Boot @SpringBootApplication、SpringApplication 类

春天启动 @SpringBootApplication 注释

Spring Boot @SpringBootApplication 注释用来标记一个声明一个或多个 @Bean 方法的配置类,并引发 auto-configuration 和组件扫描。

春天游艇应用程序类

Spring Boot‘SpringApplication’类用于从Java的主要方法启动和启动一个Spring应用程序。这个类会自动从类路径创建ApplicationContext,扫描配置类并启动应用程序。

SpringBoot 应用程序和 SpringApplication 示例

Spring RestController上的最后一本教程中,我们创建了一个 Spring RESTful 网页服务,并在 Tomcat 上部署了它,我们不得不创建 web.xml 和 Spring 背景文件,我们还不得不手动添加 Spring MVC 依赖并管理它们的版本,在这里我们将更改项目以运行作为一个 Spring Boot 应用程序并摆脱配置文件,这将有助于快速测试我们的应用程序逻辑,因为我们不必手动构建和部署项目到外部 Tomcat 服务器。

您应该从我们的 GitHub 存储库查看现有项目,在以下部分,我们将对项目文件做出必要的更改。

Below image shows our final project structure. SpringBootApplication and SpringApplication Example

添加 Spring Boot Maven 依赖

第一步是清理pom.xml文件并将其配置为Spring Boot。由于它是REST网络服务,我们只需要spring-boot-starter-web依赖性。然而,我们将不得不保持JAXB依赖性,因为我们在Java 10上运行,我们也希望支持XML请求和响应。我们还需要添加spring-boot-maven-plugin插件,这个插件允许我们运行我们的简单的Java应用程序作为春季启动应用程序。

 1<project xmlns="https://maven.apache.org/POM/4.0.0"
 2    xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
 3    xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
 4    <modelVersion>4.0.0</modelVersion>
 5    <groupId>Spring-RestController</groupId>
 6    <artifactId>Spring-RestController</artifactId>
 7    <version>0.0.1-SNAPSHOT</version>
 8    <packaging>war</packaging>
 9
10    <parent>
11    	<groupId>org.springframework.boot</groupId>
12    	<artifactId>spring-boot-starter-parent</artifactId>
13    	<version>2.0.2.RELEASE</version>
14    	<relativePath /> <!-- lookup parent from repository -->
15    </parent>
16    <properties>
17    	<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
18    	<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
19    	<java.version>10</java.version>
20    </properties>
21    <dependencies>
22    	<dependency>
23    		<groupId>org.springframework.boot</groupId>
24    		<artifactId>spring-boot-starter-web</artifactId>
25    	</dependency>
26
27    	<!-- JAXB for XML Response needed to explicitly define from Java 9 onwards -->
28
29    	<dependency>
30    		<groupId>javax.xml.bind</groupId>
31    		<artifactId>jaxb-api</artifactId>
32    	</dependency>
33    	<dependency>
34    		<groupId>org.glassfish.jaxb</groupId>
35    		<artifactId>jaxb-runtime</artifactId>
36    		<version>2.3.0</version>
37    		<scope>runtime</scope>
38    	</dependency>
39    	<dependency>
40    		<groupId>javax.activation</groupId>
41    		<artifactId>javax.activation-api</artifactId>
42    		<version>1.2.0</version>
43    	</dependency>
44    </dependencies>
45
46    <build>
47    	<!-- added to remove Version from WAR file -->
48    	<finalName>${project.artifactId}</finalName>
49    	<plugins>
50    		<plugin>
51    			<groupId>org.springframework.boot</groupId>
52    			<artifactId>spring-boot-maven-plugin</artifactId>
53    		</plugin>
54    	</plugins>
55    </build>
56</project>

我们可以删除 WebContent 目录或将其留下,它不会被我们的 Spring Boot 应用程序使用。

春天应用程序班级

现在我们必须用主方法创建一个 java 类,用@SpringBootApplication的注释来标记它,然后调用SpringApplication.run()的方法。

 1package com.journaldev.spring;
 2
 3import org.springframework.boot.SpringApplication;
 4import org.springframework.boot.autoconfigure.SpringBootApplication;
 5
 6@SpringBootApplication
 7public class SpringBootRestApplication {
 8
 9    public static void main(String[] args) {
10    	SpringApplication.run(SpringBootRestApplication.class, args);
11    }
12}

只需运行类作为Java应用程序,它将产生接下来的输出。我已经删除了一些我们在这里不关心的日志。

 12018-06-18 14:33:51.276 INFO 3830 --- [           main] c.j.spring.SpringBootRestApplication     : Starting SpringBootRestApplication on pankaj with PID 3830 (/Users/pankaj/Documents/eclipse-jee-workspace/Spring-RestController/target/classes started by pankaj in /Users/pankaj/Documents/eclipse-jee-workspace/Spring-RestController)
 22018-06-18 14:33:51.280 INFO 3830 --- [           main] c.j.spring.SpringBootRestApplication     : No active profile set, falling back to default profiles: default
 32018-06-18 14:33:51.332 INFO 3830 --- [           main] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@38467116: startup date [Mon Jun 18 14:33:51 IST 2018]; root of context hierarchy
 42018-06-18 14:33:52.311 INFO 3830 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
 52018-06-18 14:33:52.344 INFO 3830 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
 62018-06-18 14:33:52.344 INFO 3830 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.31
 72018-06-18 14:33:52.453 INFO 3830 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
 82018-06-18 14:33:52.453 INFO 3830 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1127 ms
 92018-06-18 14:33:52.564 INFO 3830 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Servlet dispatcherServlet mapped to [/]
102018-06-18 14:33:52.927 INFO 3830 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/rest/employee/get/{id}],methods=[GET]}" onto public com.journaldev.spring.model.Employee com.journaldev.spring.controller.EmployeeRestController.getEmployeeByID(int)
112018-06-18 14:33:52.928 INFO 3830 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/rest/employee/getAll],methods=[GET]}" onto public java.util.List<com.journaldev.spring.model.Employee> com.journaldev.spring.controller.EmployeeRestController.getAllEmployees()
122018-06-18 14:33:52.929 INFO 3830 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/rest/employee/create],methods=[POST]}" onto public com.journaldev.spring.model.Employee com.journaldev.spring.controller.EmployeeRestController.createEmployee(com.journaldev.spring.model.Employee)
132018-06-18 14:33:52.929 INFO 3830 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/rest/employee/search/{name}],methods=[GET]}" onto public com.journaldev.spring.model.Employee com.journaldev.spring.controller.EmployeeRestController.getEmployeeByName(java.lang.String)
142018-06-18 14:33:52.929 INFO 3830 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/rest/employee/delete/{id}],methods=[DELETE]}" onto public com.journaldev.spring.model.Employee com.journaldev.spring.controller.EmployeeRestController.deleteEmployeeByID(int)
152018-06-18 14:33:53.079 INFO 3830 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
162018-06-18 14:33:53.118 INFO 3830 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
172018-06-18 14:33:53.124 INFO 3830 --- [           main] c.j.spring.SpringBootRestApplication     : Started SpringBootRestApplication in 2.204 seconds (JVM running for 2.633)

我们可以从日志中推断一些重要的点:

Spring Boot Application Process ID是3830 2. Spring Boot Application正在在端口8080上启动Tomcat 3.我们的应用程序背景路径是``。这意味着在召唤我们的API时,我们不需要提供服务链接 4.日志器打印了所有已配置的API,参见消息Mapped {[/rest/employee/get/{id}],methods=[GET]}`等。

Below image shows an example invocation of the APIs exposed by our Spring Boot Application. Spring Boot Application Example

SpringBoot应用程序扫描BasePackages

默认情况下,SpringApplication 会扫描配置类包和其所有子包,所以如果我们的SpringBootRestApplication类在com.journaldev.spring.main包中,那么它不会扫描com.journaldev.spring.controller包,我们可以使用 SpringBootApplication 扫描BasePackages 属性来修复这种情况。

1@SpringBootApplication(scanBasePackages="com.journaldev.spring")
2public class SpringBootRestApplication {
3}

Spring Boot 自动配置豆类

由于Spring Boot提供自动配置,所以有很多豆子可以通过它进行配置,我们可以使用下面的代码片段来获取这些豆子的列表。

1ApplicationContext ctx = SpringApplication.run(SpringBootRestApplication.class, args);
2String[] beans = ctx.getBeanDefinitionNames();
3for(String s : beans) System.out.println(s);

下面是由我们的春天启动应用程序配置的豆类列表。

  1org.springframework.context.annotation.internalConfigurationAnnotationProcessor
  2org.springframework.context.annotation.internalAutowiredAnnotationProcessor
  3org.springframework.context.annotation.internalRequiredAnnotationProcessor
  4org.springframework.context.annotation.internalCommonAnnotationProcessor
  5org.springframework.context.event.internalEventListenerProcessor
  6org.springframework.context.event.internalEventListenerFactory
  7springBootRestApplication
  8org.springframework.boot.autoconfigure.internalCachingMetadataReaderFactory
  9employeeRestController
 10employeeRepository
 11org.springframework.boot.autoconfigure.AutoConfigurationPackages
 12org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration
 13org.springframework.boot.autoconfigure.condition.BeanTypeRegistry
 14propertySourcesPlaceholderConfigurer
 15org.springframework.boot.autoconfigure.websocket.servlet.WebSocketServletAutoConfiguration$TomcatWebSocketConfiguration
 16websocketContainerCustomizer
 17org.springframework.boot.autoconfigure.websocket.servlet.WebSocketServletAutoConfiguration
 18org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryConfiguration$EmbeddedTomcat
 19tomcatServletWebServerFactory
 20org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryAutoConfiguration
 21servletWebServerFactoryCustomizer
 22tomcatServletWebServerFactoryCustomizer
 23server-org.springframework.boot.autoconfigure.web.ServerProperties
 24org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor
 25org.springframework.boot.context.properties.ConfigurationBeanFactoryMetadata
 26webServerFactoryCustomizerBeanPostProcessor
 27errorPageRegistrarBeanPostProcessor
 28org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration$DispatcherServletConfiguration
 29dispatcherServlet
 30mainDispatcherServletPathProvider
 31spring.mvc-org.springframework.boot.autoconfigure.web.servlet.WebMvcProperties
 32org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration$DispatcherServletRegistrationConfiguration
 33dispatcherServletRegistration
 34org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration
 35org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration
 36defaultValidator
 37methodValidationPostProcessor
 38org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration
 39error
 40beanNameViewResolver
 41org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration$DefaultErrorViewResolverConfiguration
 42conventionErrorViewResolver
 43org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration
 44errorAttributes
 45basicErrorController
 46errorPageCustomizer
 47preserveErrorControllerTargetClassPostProcessor
 48spring.resources-org.springframework.boot.autoconfigure.web.ResourceProperties
 49org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter$FaviconConfiguration
 50faviconHandlerMapping
 51faviconRequestHandler
 52org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration$EnableWebMvcConfiguration
 53requestMappingHandlerAdapter
 54requestMappingHandlerMapping
 55mvcConversionService
 56mvcValidator
 57mvcContentNegotiationManager
 58mvcPathMatcher
 59mvcUrlPathHelper
 60viewControllerHandlerMapping
 61beanNameHandlerMapping
 62resourceHandlerMapping
 63mvcResourceUrlProvider
 64defaultServletHandlerMapping
 65mvcUriComponentsContributor
 66httpRequestHandlerAdapter
 67simpleControllerHandlerAdapter
 68handlerExceptionResolver
 69mvcViewResolver
 70mvcHandlerMappingIntrospector
 71org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter
 72defaultViewResolver
 73viewResolver
 74welcomePageHandlerMapping
 75requestContextFilter
 76org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration
 77hiddenHttpMethodFilter
 78httpPutFormContentFilter
 79org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration
 80mbeanExporter
 81objectNamingStrategy
 82mbeanServer
 83org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration
 84org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration$Jackson2ObjectMapperBuilderCustomizerConfiguration
 85standardJacksonObjectMapperBuilderCustomizer
 86spring.jackson-org.springframework.boot.autoconfigure.jackson.JacksonProperties
 87org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration$JacksonObjectMapperBuilderConfiguration
 88jacksonObjectMapperBuilder
 89org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration$ParameterNamesModuleConfiguration
 90parameterNamesModule
 91org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration$JacksonObjectMapperConfiguration
 92jacksonObjectMapper
 93org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration
 94jsonComponentModule
 95org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration$StringHttpMessageConverterConfiguration
 96stringHttpMessageConverter
 97spring.http.encoding-org.springframework.boot.autoconfigure.http.HttpEncodingProperties
 98org.springframework.boot.autoconfigure.http.JacksonHttpMessageConvertersConfiguration$MappingJackson2HttpMessageConverterConfiguration
 99mappingJackson2HttpMessageConverter
100org.springframework.boot.autoconfigure.http.JacksonHttpMessageConvertersConfiguration
101org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration
102messageConverters
103org.springframework.boot.autoconfigure.http.codec.CodecsAutoConfiguration$JacksonCodecConfiguration
104jacksonCodecCustomizer
105org.springframework.boot.autoconfigure.http.codec.CodecsAutoConfiguration
106org.springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration
107spring.info-org.springframework.boot.autoconfigure.info.ProjectInfoProperties
108org.springframework.boot.autoconfigure.security.reactive.ReactiveSecurityAutoConfiguration
109spring.security-org.springframework.boot.autoconfigure.security.SecurityProperties
110org.springframework.boot.autoconfigure.web.client.RestTemplateAutoConfiguration
111restTemplateBuilder
112org.springframework.boot.autoconfigure.web.embedded.EmbeddedWebServerFactoryCustomizerAutoConfiguration$TomcatWebServerFactoryCustomizerConfiguration
113tomcatWebServerFactoryCustomizer
114org.springframework.boot.autoconfigure.web.embedded.EmbeddedWebServerFactoryCustomizerAutoConfiguration
115org.springframework.boot.autoconfigure.web.servlet.HttpEncodingAutoConfiguration
116characterEncodingFilter
117localeCharsetMappingsCustomizer
118org.springframework.boot.autoconfigure.web.servlet.MultipartAutoConfiguration
119multipartConfigElement
120multipartResolver
121spring.servlet.multipart-org.springframework.boot.autoconfigure.web.servlet.MultipartProperties

我们可以通过使用 @SpringBootApplication excludeexcludeName 属性来激活我们的春天启动应用程序来优化。

1@SpringBootApplication(scanBasePackages = "com.journaldev.spring", exclude = {
2org.springframework.boot.autoconfigure.web.servlet.MultipartAutoConfiguration.class, org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration.class })
3public class SpringBootRestApplication {
4}

请注意,如果我们试图排除任何非自动配置类,我们会收到错误,我们的应用程序将无法启动。

1@SpringBootApplication(scanBasePackages = "com.journaldev.spring", exclude = {com.journaldev.spring.controller.EmployeeRestController.class })
2public class SpringBootRestApplication {
3}

上面的代码片段会引发以下错误:

12018-06-18 15:10:43.602 ERROR 3899 --- [main] o.s.boot.SpringApplication: Application run failed
2
3java.lang.IllegalStateException: The following classes could not be excluded because they are not auto-configuration classes:
4    - com.journaldev.spring.controller.EmployeeRestController

这就是SpringBootApplication的注释和SpringApplication的例子。

您可以从我们的 GitHub 存储库下载最终项目。

Published At
Categories with 技术
Tagged with
comments powered by Disqus