Spring Boot @SpringBootApplication Аннотация
Аннотация @SpringBootApplication
в Spring Boot используется для пометки класса конфигурации, который объявляет один или несколько методов @Bean
, а также запускает автоконфигурацию
и сканирование компонентов. Это то же самое, что объявление класса с @Configuration, @EnableAutoConfiguration и @ComponentScan аннотациями.
Spring Boot Класс SpringApplication
Класс SpringApplication
в Spring Boot используется для запуска приложения Spring из метода main в Java. Этот класс автоматически создает ApplicationContext
из classpath, сканирует конфигурационные классы и запускает приложение. Этот класс очень полезен при запуске Spring MVC или приложения Spring REST с использованием Spring Boot.
Пример SpringBootApplication и SpringApplication
В последнем уроке по Spring RestController мы создали RESTful веб-сервис Spring и развернули его на Tomcat. Нам пришлось создать web.xml
и файл контекста Spring. Мы также должны были вручную добавить зависимости Spring MVC и управлять их версиями. Здесь мы изменим проект на запуск как приложение Spring Boot и избавимся от конфигурационных файлов. Это поможет быстро тестировать логику нашего приложения, потому что нам не придется вручную собирать и развертывать проект на внешнем сервере Tomcat.
Вы должны проверить существующий проект из нашего репозитория GitHub, в следующих разделах мы внесем необходимые изменения в файлы проекта.
Ниже приведена структура нашего конечного проекта.
Добавление зависимостей Spring Boot Maven
Первым шагом является очистка файла pom.xml
и его настройка для Spring Boot. Поскольку это REST веб-сервис, нам нужна только зависимость spring-boot-starter-web
. Однако мы должны сохранить зависимости JAXB, потому что мы используем Java 10 и хотим поддерживать также запросы и ответы XML. Также нам придется добавить плагин spring-boot-maven-plugin
, этот плагин позволяет запускать наше простое java-приложение как приложение spring boot. Вот наш обновленный файл pom.xml.
<project xmlns="https://maven.apache.org/POM/4.0.0"
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>Spring-RestController</groupId>
<artifactId>Spring-RestController</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.2.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>10</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- JAXB for XML Response needed to explicitly define from Java 9 onwards -->
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
<version>2.3.0</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>javax.activation-api</artifactId>
<version>1.2.0</version>
</dependency>
</dependencies>
<build>
<!-- added to remove Version from WAR file -->
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Мы можем удалить каталог WebContent или оставить его как есть, он не будет использоваться нашим приложением Spring Boot.
Класс приложения Spring Boot
Теперь нам нужно создать java-класс с основным методом, пометить его аннотацией @SpringBootApplication
и вызвать метод SpringApplication.run()
.
package com.journaldev.spring;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootRestApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootRestApplication.class, args);
}
}
Просто запустите класс как приложение Java, и он выведет следующий результат. Я убрал некоторые логгеры, которые нас не интересуют. Приложение не завершится и будет ожидать запросов клиента.
2018-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)
2018-06-18 14:33:51.280 INFO 3830 --- [ main] c.j.spring.SpringBootRestApplication : No active profile set, falling back to default profiles: default
2018-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
2018-06-18 14:33:52.311 INFO 3830 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2018-06-18 14:33:52.344 INFO 3830 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2018-06-18 14:33:52.344 INFO 3830 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.31
2018-06-18 14:33:52.453 INFO 3830 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2018-06-18 14:33:52.453 INFO 3830 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1127 ms
2018-06-18 14:33:52.564 INFO 3830 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Servlet dispatcherServlet mapped to [/]
2018-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)
2018-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()
2018-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)
2018-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)
2018-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)
2018-06-18 14:33:53.079 INFO 3830 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2018-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 ''
2018-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 – 3830.
- Spring Boot запускает Tomcat на порту 8080.
- Контекст нашего приложения – «». Это означает, что при вызове наших API нам не нужно указывать контекст сервлета.
- Логгер выводит все настроенные API, см. сообщения
Mapped "{[/rest/employee/get/{id}],methods=[GET]}"
и так далее.
На изображении ниже показан пример вызова API, предоставленных нашим приложением Spring Boot.
SpringBootApplication scanBasePackages
По умолчанию SpringApplication сканирует пакет класса конфигурации и все его подпакеты. Так что, если наш класс SpringBootRestApplication
находится в пакете com.journaldev.spring.main
, то он не будет сканировать пакет com.journaldev.spring.controller
. Мы можем исправить эту ситуацию, используя свойство SpringBootApplication scanBasePackages.
@SpringBootApplication(scanBasePackages="com.journaldev.spring")
public class SpringBootRestApplication {
}
Автоконфигурируемые бины Spring Boot
Поскольку Spring Boot предоставляет автоконфигурацию, множество бинов настраиваются им. Мы можем получить список этих бинов, используя следующий фрагмент кода.
ApplicationContext ctx = SpringApplication.run(SpringBootRestApplication.class, args);
String[] beans = ctx.getBeanDefinitionNames();
for(String s : beans) System.out.println(s);
Ниже приведен список бинов, настроенных нашим приложением Spring Boot.
org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalRequiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
org.springframework.context.event.internalEventListenerProcessor
org.springframework.context.event.internalEventListenerFactory
springBootRestApplication
org.springframework.boot.autoconfigure.internalCachingMetadataReaderFactory
employeeRestController
employeeRepository
org.springframework.boot.autoconfigure.AutoConfigurationPackages
org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration
org.springframework.boot.autoconfigure.condition.BeanTypeRegistry
propertySourcesPlaceholderConfigurer
org.springframework.boot.autoconfigure.websocket.servlet.WebSocketServletAutoConfiguration$TomcatWebSocketConfiguration
websocketContainerCustomizer
org.springframework.boot.autoconfigure.websocket.servlet.WebSocketServletAutoConfiguration
org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryConfiguration$EmbeddedTomcat
tomcatServletWebServerFactory
org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryAutoConfiguration
servletWebServerFactoryCustomizer
tomcatServletWebServerFactoryCustomizer
server-org.springframework.boot.autoconfigure.web.ServerProperties
org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor
org.springframework.boot.context.properties.ConfigurationBeanFactoryMetadata
webServerFactoryCustomizerBeanPostProcessor
errorPageRegistrarBeanPostProcessor
org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration$DispatcherServletConfiguration
dispatcherServlet
mainDispatcherServletPathProvider
spring.mvc-org.springframework.boot.autoconfigure.web.servlet.WebMvcProperties
org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration$DispatcherServletRegistrationConfiguration
dispatcherServletRegistration
org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration
org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration
defaultValidator
methodValidationPostProcessor
org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration
error
beanNameViewResolver
org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration$DefaultErrorViewResolverConfiguration
conventionErrorViewResolver
org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration
errorAttributes
basicErrorController
errorPageCustomizer
preserveErrorControllerTargetClassPostProcessor
spring.resources-org.springframework.boot.autoconfigure.web.ResourceProperties
org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter$FaviconConfiguration
faviconHandlerMapping
faviconRequestHandler
org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration$EnableWebMvcConfiguration
requestMappingHandlerAdapter
requestMappingHandlerMapping
mvcConversionService
mvcValidator
mvcContentNegotiationManager
mvcPathMatcher
mvcUrlPathHelper
viewControllerHandlerMapping
beanNameHandlerMapping
resourceHandlerMapping
mvcResourceUrlProvider
defaultServletHandlerMapping
mvcUriComponentsContributor
httpRequestHandlerAdapter
simpleControllerHandlerAdapter
handlerExceptionResolver
mvcViewResolver
mvcHandlerMappingIntrospector
org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter
defaultViewResolver
viewResolver
welcomePageHandlerMapping
requestContextFilter
org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration
hiddenHttpMethodFilter
httpPutFormContentFilter
org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration
mbeanExporter
objectNamingStrategy
mbeanServer
org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration
org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration$Jackson2ObjectMapperBuilderCustomizerConfiguration
standardJacksonObjectMapperBuilderCustomizer
spring.jackson-org.springframework.boot.autoconfigure.jackson.JacksonProperties
org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration$JacksonObjectMapperBuilderConfiguration
jacksonObjectMapperBuilder
org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration$ParameterNamesModuleConfiguration
parameterNamesModule
org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration$JacksonObjectMapperConfiguration
jacksonObjectMapper
org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration
jsonComponentModule
org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration$StringHttpMessageConverterConfiguration
stringHttpMessageConverter
spring.http.encoding-org.springframework.boot.autoconfigure.http.HttpEncodingProperties
org.springframework.boot.autoconfigure.http.JacksonHttpMessageConvertersConfiguration$MappingJackson2HttpMessageConverterConfiguration
mappingJackson2HttpMessageConverter
org.springframework.boot.autoconfigure.http.JacksonHttpMessageConvertersConfiguration
org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration
messageConverters
org.springframework.boot.autoconfigure.http.codec.CodecsAutoConfiguration$JacksonCodecConfiguration
jacksonCodecCustomizer
org.springframework.boot.autoconfigure.http.codec.CodecsAutoConfiguration
org.springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration
spring.info-org.springframework.boot.autoconfigure.info.ProjectInfoProperties
org.springframework.boot.autoconfigure.security.reactive.ReactiveSecurityAutoConfiguration
spring.security-org.springframework.boot.autoconfigure.security.SecurityProperties
org.springframework.boot.autoconfigure.web.client.RestTemplateAutoConfiguration
restTemplateBuilder
org.springframework.boot.autoconfigure.web.embedded.EmbeddedWebServerFactoryCustomizerAutoConfiguration$TomcatWebServerFactoryCustomizerConfiguration
tomcatWebServerFactoryCustomizer
org.springframework.boot.autoconfigure.web.embedded.EmbeddedWebServerFactoryCustomizerAutoConfiguration
org.springframework.boot.autoconfigure.web.servlet.HttpEncodingAutoConfiguration
characterEncodingFilter
localeCharsetMappingsCustomizer
org.springframework.boot.autoconfigure.web.servlet.MultipartAutoConfiguration
multipartConfigElement
multipartResolver
spring.servlet.multipart-org.springframework.boot.autoconfigure.web.servlet.MultipartProperties
Это огромный список, есть много автоконфигурируемых бинов, которые мы не используем. Мы можем оптимизировать наше приложение Spring Boot, отключив их с помощью свойств exclude
или excludeName
в аннотации @SpringBootApplication. Ниже приведен фрагмент кода, который отключает автоконфигурацию JMX и Multipart.
@SpringBootApplication(scanBasePackages = "com.journaldev.spring", exclude = {
org.springframework.boot.autoconfigure.web.servlet.MultipartAutoConfiguration.class, org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration.class })
public class SpringBootRestApplication {
}
Обратите внимание, что если мы попытаемся исключить какие-либо неавтоконфигурируемые классы, мы получим ошибку, и наше приложение не запустится.
@SpringBootApplication(scanBasePackages = "com.journaldev.spring", exclude = {com.journaldev.spring.controller.EmployeeRestController.class })
public class SpringBootRestApplication {
}
Приведенный выше фрагмент кода вызовет следующую ошибку:
2018-06-18 15:10:43.602 ERROR 3899 --- [main] o.s.boot.SpringApplication: Application run failed
java.lang.IllegalStateException: The following classes could not be excluded because they are not auto-configuration classes:
- com.journaldev.spring.controller.EmployeeRestController
Это все для аннотации SpringBootApplication
и примера SpringApplication
.
Вы можете загрузить окончательный проект из нашего репозитория GitHub.
Source:
https://www.digitalocean.com/community/tutorials/springbootapplication-springapplication