Spring Boot @SpringBootApplication Annotation
De Spring Boot @SpringBootApplication
-annotatie wordt gebruikt om een configuratieklasse aan te duiden die één of meer @Bean
-methoden declareert en ook auto-configuratie
en component scanning activeert. Het is hetzelfde als het declareren van een klasse met @Configuration, @EnableAutoConfiguration en @ComponentScan-annotaties.
Spring Boot SpringApplication-klasse
Spring Boot SpringApplication
class wordt gebruikt om een Spring-toepassing te starten en te lanceren vanuit een Java-hoofdmethode. Deze klasse maakt automatisch de ApplicationContext
aan vanuit de klassepad, scant de configuratieklassen en lanceert de toepassing. Deze klasse is zeer nuttig bij het starten van een Spring MVC of Spring REST-toepassing met behulp van Spring Boot.
SpringBootApplication en SpringApplication Voorbeeld
In de laatste tutorial over Spring RestController hebben we een Spring RESTful webservice gemaakt en deze geïmplementeerd op Tomcat. We moesten web.xml
en het spring-contextbestand aanmaken. We moesten ook handmatig Spring MVC-afhankelijkheden toevoegen en hun versies beheren. Hier zullen we het project wijzigen om uit te voeren als een Spring Boot-toepassing en configuratiebestanden weg te laten. Dit zal helpen bij het snel testen van onze toepassingslogica omdat we het project niet handmatig hoeven te bouwen en implementeren naar de externe Tomcat-server.
U moet het bestaande project controleren vanuit onze GitHub Repository, in de volgende secties zullen we noodzakelijke wijzigingen aanbrengen in de projectbestanden.
Onderstaande afbeelding toont onze uiteindelijke projectstructuur.
Het toevoegen van Spring Boot Maven-afhankelijkheden
De eerste stap is het opschonen van het pom.xml
-bestand en het configureren voor Spring Boot. Aangezien het een REST-webservice is, hebben we alleen de spring-boot-starter-web
-afhankelijkheid nodig. We moeten echter de JAXB-afhankelijkheden behouden omdat we op Java 10 draaien en ook XML-verzoeken en -reacties willen ondersteunen. We moeten ook de spring-boot-maven-plugin
-plugin toevoegen; deze plugin stelt ons in staat om onze eenvoudige Java-toepassing als een Spring Boot-toepassing uit te voeren. Hier is ons bijgewerkte pom.xml-bestand.
<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>
We kunnen de WebContent-map verwijderen of ongewijzigd laten, omdat deze niet zal worden gebruikt door onze Spring Boot-toepassing.
Spring Boot-toepassingsklasse
Nu moeten we een Java-klasse maken met de hoofdmethode, deze markeren met de @SpringBootApplication
-annotatie en de methode SpringApplication.run()
aanroepen.
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);
}
}
Voer gewoon de klasse uit als een Java-toepassing en het zal de volgende uitvoer produceren. Ik heb enkele loggers verwijderd waar we hier niet om geven. De toepassing zal niet afsluiten en wachten op clientverzoeken.
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)
Enkele belangrijke punten die we uit de logs kunnen afleiden:
- Spring Boot Application Process ID is 3830.
- Spring Boot Application start Tomcat op poort 8080.
- Ons applicatiecontextpad is “”. Dat betekent dat we bij het aanroepen van onze API’s geen servletcontext hoeven op te geven.
- De logger drukt alle API’s af die geconfigureerd zijn, zie berichten
Mapped "{[/rest/employee/get/{id}],methods=[GET]}"
enz.
De onderstaande afbeelding toont een voorbeeld van de oproepen van de API’s die worden blootgesteld door onze Spring Boot-toepassing.
SpringBootApplication scanBasePackages
Standaard scant SpringApplication het pakket van de configuratieklasse en al zijn subpakketten. Dus als onze SpringBootRestApplication
-klasse zich in het pakket com.journaldev.spring.main
bevindt, zal het niet het pakket com.journaldev.spring.controller
scannen. We kunnen deze situatie oplossen door de eigenschap SpringBootApplication scanBasePackages te gebruiken.
@SpringBootApplication(scanBasePackages="com.journaldev.spring")
public class SpringBootRestApplication {
}
Spring Boot Automatisch geconfigureerde Beans
Aangezien Spring Boot automatische configuratie biedt, worden er veel beans geconfigureerd door het. We kunnen een lijst van deze beans krijgen met behulp van onderstaande codefragment.
ApplicationContext ctx = SpringApplication.run(SpringBootRestApplication.class, args);
String[] beans = ctx.getBeanDefinitionNames();
for(String s : beans) System.out.println(s);
Hieronder staat de lijst van beans geconfigureerd door onze Spring Boot-toepassing.
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
Dat is een enorme lijst, er zijn veel automatisch geconfigureerde beans die we niet gebruiken. We kunnen onze Spring Boot-toepassing optimaliseren door deze uit te schakelen met behulp van de @SpringBootApplication eigenschap exclude
of excludeName
. Onderstaand codefragment zal JMX- en Multipart-autoconfiguratie uitschakelen.
@SpringBootApplication(scanBasePackages = "com.journaldev.spring", exclude = {
org.springframework.boot.autoconfigure.web.servlet.MultipartAutoConfiguration.class, org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration.class })
public class SpringBootRestApplication {
}
Merk op dat als we proberen om niet-automatische configuratie klassen uit te sluiten, we een foutmelding krijgen en onze toepassing niet zal starten.
@SpringBootApplication(scanBasePackages = "com.journaldev.spring", exclude = {com.journaldev.spring.controller.EmployeeRestController.class })
public class SpringBootRestApplication {
}
Het bovenstaande codefragment zal de volgende foutmelding veroorzaken:
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
Dat is alles voor de SpringBootApplication
annotatie en het SpringApplication
voorbeeld.
U kunt het eindproject downloaden van onze GitHub Repository.
Source:
https://www.digitalocean.com/community/tutorials/springbootapplication-springapplication