Spring Bootの@SpringBootApplication、SpringApplicationクラス

スプリングブートの@スプリングブートアプリケーションアノテーション

Spring Bootの@SpringBootApplicationアノテーションは、1つ以上の@Beanメソッドを宣言し、自動設定とコンポーネントスキャンもトリガーする設定クラスをマークするために使用されます。これは、@Configuration、@EnableAutoConfiguration、および@ComponentScanアノテーションを使用してクラスを宣言するのと同じです。

スプリングブートのSpringApplicationクラス

Spring BootのSpringApplicationクラスは、JavaのmainメソッドからSpringアプリケーションを起動しブートストラップするために使用されます。このクラスは自動的にクラスパスからApplicationContextを作成し、設定クラスをスキャンし、アプリケーションを起動します。このクラスは、Spring Bootを使用してSpring MVCやSpring RESTアプリケーションを起動する際に非常に役立ちます。

SpringBootApplicationとSpringApplicationの例

前回のSpring RestControllerチュートリアルでは、SpringのRESTfulなWebサービスを作成し、Tomcatにデプロイしました。web.xmlとspringのコンテキストファイルを作成する必要がありました。また、Spring MVCの依存関係を手動で追加し、そのバージョンを管理する必要がありました。ここでは、プロジェクトをSpring Bootアプリケーションとして実行し、設定ファイルを不要にします。これにより、プロジェクトを手動でビルドして外部のTomcatサーバーにデプロイする必要がなくなり、アプリケーションロジックの素早いテストが可能になります。

私たちのGitHubリポジトリから既存のプロジェクトを確認してください。以下のセクションでは、プロジェクトファイルに必要な変更を行います。

SpringBootApplication and SpringApplication Example

Spring Boot Mavenの依存関係を追加する。

最初のステップは、pom.xmlファイルを整理し、Spring Bootに設定することです。これはRESTウェブサービスなので、spring-boot-starter-webの依存関係だけが必要です。ただし、Java 10上で実行され、XMLリクエストとレスポンスもサポートする必要があるため、JAXBの依存関係を保持する必要があります。また、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アプリケーションでは使用されません。

スプリングブートアプリケーションクラス

今、私たちはmainメソッドを持つJavaクラスを作成し、@SpringBootApplicationアノテーションを付け、SpringApplication.run()メソッドを呼び出さなければなりません。

package com.scdev.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 scdev with PID 3830 (/Users/scdev/Documents/eclipse-jee-workspace/Spring-RestController/target/classes started by scdev in /Users/scdev/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.scdev.spring.model.Employee com.scdev.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.scdev.spring.model.Employee> com.scdev.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.scdev.spring.model.Employee com.scdev.spring.controller.EmployeeRestController.createEmployee(com.scdev.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.scdev.spring.model.Employee com.scdev.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.scdev.spring.model.Employee com.scdev.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)

ログから推測できる重要なポイントは以下の通りです。

    1. Spring BootアプリケーションのプロセスIDは3830です。

 

    1. Spring Bootアプリケーションは、ポート8080でTomcatを起動しています。

 

    1. 私たちのアプリケーションのコンテキストパスは「」です。つまり、APIを呼び出す際にはサーブレットコンテキストを指定する必要はありません。

 

    ロガーは設定されているすべてのAPIを出力します。”Mapped “{[/rest/employee/get/{id}],methods=[GET]}”などのメッセージが表示されます。
Spring Boot Application Example

@SpringBootApplicationアノテーションのscanBasePackages

デフォルトでは、SpringApplicationは構成クラスのパッケージとそのサブパッケージをスキャンします。つまり、SpringBootRestApplicationクラスがcom.scdev.spring.mainパッケージにある場合、com.scdev.spring.controllerパッケージはスキャンされません。しかし、SpringBootApplicationのscanBasePackagesプロパティを使用することで、この状況を修正することができます。

@SpringBootApplication(scanBasePackages="com.scdev.spring")
public class SpringBootRestApplication {
}

Spring Boot自動構成されたビーンズ

以下のコードスニペットを使用すると、Spring Bootが自動設定を提供するため、多くのBeanがそれによって設定されます。これらのBeanのリストを取得することができます。

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

私たちのSpring Bootアプリケーションで構成された豆のリストは以下の通りです。 (Watashitachi no Spring Boot apurikēshon de kōsei sareta mame no risuto wa ikkō desu.)

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

それは巨大なリストですね。私たちが使用していない多くの自動設定されたビーンがあります。@SpringBootApplication excludeまたはexcludeNameプロパティを使用して、これらを無効にすることで、私たちのSpring Bootアプリケーションを最適化することができます。以下のコードスニペットは、JMXとマルチパートの自動設定を無効にします。

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

非自動設定クラスを除外しようとすると、エラーが発生し、アプリケーションが起動しなくなることに注意してください。

@SpringBootApplication(scanBasePackages = "com.scdev.spring", exclude = {com.scdev.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.scdev.spring.controller.EmployeeRestController

SpringBootApplicationアノテーションとSpringApplicationの例については以上です。

私たちのGitHubリポジトリから最終プロジェクトをダウンロードできます。

コメントを残す 0

Your email address will not be published. Required fields are marked *