LoginSignup
6
9

More than 5 years have passed since last update.

Spring Boot Reference Guide メモ

Last updated at Posted at 2016-05-19

Spring Boot Reference Guideの自分用メモ(下書き中)

SpringBootを使用したWebアプリを開発しようとしています。
雰囲気的には簡単そうではあるものの、良くわからないところが多いので、まずはReference Guideを読んでいて必要そうな項目をピックアップしてメモしています。

原文と日本語メモの対比になっていますが、日本語メモは原文を訳したものではなく、自分用のメモである点に注意です。
構成ツールは主にGradleに関係のあるものしかピックアップしていません。

ReferenceGuideを読んでみたいけど、英語はチョット・・・。
という方のお役に立てば幸いです。

#Qiitaへの投稿は初めてで、使いこなせていない部分が多々あり恐縮です。


参照元
Spring Boot Reference Guide (version 1.3.5.RELEASE)

11.3.1 The @RestController and @RequestMapping annotations

The @RequestMapping annotation provides “routing” information. It is telling Spring that any HTTP request with the path “/” should be mapped to the home method. The @RestController annotation tells Spring to render the resulting string directly back to the caller.

@RequestMapping annotationにはルーティング情報を記載する。
@RequestMapping("/hello")とすると、リクエストURLの/helloパスを処理することを宣言したことになる。

11.3.2 The @EnableAutoConfiguration annotation

自動コンフィギュレーションの有効化

11.3.3 The “main” method

The final part of our application is the main method. This is just a standard method that follows the Java convention for an application entry point. Our main method delegates to Spring Boot’s SpringApplication class by calling run.

main()メソッドを用意して、その中でSpringApplication.run()を実行する。
run()メソッドの引数には、main()メソッドを実装したクラスを設定する。
コマンドライン引数はrun()メソッドに透過的に渡される(?)

13.3 Gradle

Gradle users can directly import “starter POMs” in their dependencies section. Unlike Maven, there is no “super parent” to import to share some configuration.

Gradleユーザーは、"starter POMs"をdependencies sectionに記載する。
mavenのような“super parent” は存在しない。

The spring-boot-gradle-plugin is also available and provides tasks to create executable jars and run projects from source.

spring-boot-gradle-pluginを利用すると、実行可能jarやタスクの実行が可能

13.5 Starter POMs

Table 13.1. Spring Boot application starters

Starter POMsの一覧はTable 13.1を参照。
#編集注記:一度見ておいたほうがよさそう。

Finally, Spring Boot includes some starters that can be used if you want to exclude or swap specific technical facets.

Table 13.3. Spring Boot technical starters

Spring Bootはいくつかのstarterを含んでいるが、除外したり交換したりできる。

14. Structuring your code

フォルダー構成

14.1 Using the “default” package

When a class doesn’t include a package declaration it is considered to be in the “default package”. The use of the “default package” is generally discouraged, and should be avoided. It can cause particular problems for Spring Boot applications that use @ComponentScan, @EntityScan or @SpringBootApplication annotations, since every class from every jar, will be read.

"default package"の使用はさけるべし。

We recommend that you follow Java’s recommended package naming conventions and use a reversed domain name (for example, com.example.project).

逆ドメイン形式のパッケージが望ましい。

14.2 Locating the main application class

We generally recommend that you locate your main application class in a root package above other classes. The @EnableAutoConfiguration annotation is often placed on your main class, and it implicitly defines a base “search package” for certain items. For example, if you are writing a JPA application, the package of the @EnableAutoConfiguration annotated class will be used to search for @Entity items.

ルートパッケージにメインアプリケーションクラスを配置したほうがいい。
@EnableAutoConfigurationを設定したクラスのパッケージ配下がスキャン対象になる。
(通常メインアプリケーションクラスに@EnableAutoConfigurationを設定する)

15. Configuration classes

Spring Boot favors Java-based configuration. Although it is possible to call SpringApplication.run() with an XML source, we generally recommend that your primary source is a @Configuration class. Usually the class that defines the main method is also a good candidate as the primary @Configuration.

ConfigurationはXMLファイルよりJavaクラスベースがお勧め。(だそうです)

15.2 Importing XML configuration

If you absolutely must use XML based configuration, we recommend that you still start with a @Configuration class. You can then use an additional @ImportResource annotation to load XML configuration files.

どうしてもConfigurationをXMLで行いたい場合、@ImportResourceを使うことができる。

16. Auto-configuration

You need to opt-in to auto-configuration by adding the @EnableAutoConfiguration or @SpringBootApplication annotations to one of your @Configuration classes.

自動設定を有効にするには、@Configurationクラスに@EnableAutoConfiguration@SpringBootApplicationを設定します。

#編集注記:実は@SpringBootApplication@EnableAutoConfiguration@Configurationが含まれている。

16.1 Gradually replacing auto-configuration

Auto-configuration is noninvasive, at any point you can start to define your own configuration to replace specific parts of the auto-configuration. For example, if you add your own DataSource bean, the default embedded database support will back away.

自動設定は、置き換えることができますよ。

If you need to find out what auto-configuration is currently being applied, and why, start your application with the --debug switch. This will log an auto-configuration report to the console.

--debugスイッチを使うと、consoleに現在の自動設定が出力されます。

16.2 Disabling specific auto-configuration

If you find that specific auto-configure classes are being applied that you don’t want, you can use the exclude attribute of @EnableAutoConfiguration to disable them.

@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})で指定した自動設定を無効化することができます。

If the class is not on the classpath, you can use the excludeName attribute of the annotation and specify the fully qualified name instead. Finally, you can also control the list of auto-configuration classes to exclude via the spring.autoconfigure.exclude property.

除外するクラスがclasspathに無い場合はexcludeNameを指定することもできる。
また、spring.autoconfigure.excludeプロパティでも同様のことが可能。

17. Spring Beans and dependency injection

You are free to use any of the standard Spring Framework techniques to define your beans and their injected dependencies. For simplicity, we often find that using @ComponentScan to find your beans, in combination with @Autowired constructor injection works well.
If you structure your code as suggested above (locating your application class in a root package), you can add @ComponentScan without any arguments. All of your application components (@Component, @Service, @Repository, @Controller etc.) will be automatically registered as Spring Beans.

Here is an example @Service Bean that uses constructor injection to obtain a required RiskAssessor bean.

パッケージルートのクラスに@ComponentScanを付与することで@AutowiredによるDIがうまく動作する。
@ComponetScanの作用によってアプリケーション・コンポーネント( @Controllerなど@Component@Service@Repository 、 )が自動的に登録される。

18. Using the @SpringBootApplication annotation

The @SpringBootApplication annotation is equivalent to using @Configuration, @EnableAutoConfiguration and @ComponentScan with their default attributes:

@SpringBootApplicationアノテーションは、デフォルトの属性で@Configuration@EnableAutoConfiguration@ComponentScanを使用するのと同じです。

19.2 Running as a packaged application

If you use the Spring Boot Maven or Gradle plugins to create an executable jar you can run your application using java -jar. For example:

SpringBootのexecutable jarの実行は簡単。java -jar コマンドを使います。

$ java -jar target/myproject-0.0.1-SNAPSHOT.jar

19.4 Using the Gradle plugin

The Spring Boot Gradle plugin also includes a bootRun task which can be used to run your application in an exploded form. The bootRun task is added whenever you import the spring-boot-gradle-plugin:

gradleプラグインでは、以下のタスクでアプリケーションを実行することもできます。

gradle bootRun

これはオプションの指定方法 

$ export JAVA_OPTS=-Xmx1024m -XX:MaxPermSize=128M -Djava.security.egd=file:/dev/./urandom

19.5 Hot swapping

Since Spring Boot applications are just plain Java applications, JVM hot-swapping should work out of the box.

SpringBootアプリケーションは純粋なJavaアプリケーションであるため、JVMの Hot-Swappingも動作する。
spring-boot-devtools moduleを組み込めば、Hot swappingが使える。

20. Developer tools

Spring Boot includes an additional set of tools that can make the application development experience a little more pleasant. The spring-boot-devtools module can be included in any project to provide additional development-time features. To include devtools support, simply add the module dependency to your build:

Developer toolsは以下のように依存関係を構築するだけで使えるようになる。

Gradle

dependencies {
compile("org.springframework.boot:spring-boot-devtools")
}

Developer tools are automatically disabled when running a fully packaged application. If your application is launched using java -jar or if it’s started using a special classloader, then it is considered a “production application”.

Developer Toolsはfully packaged application(注:たぶんExecutable jarファイルとか)の場合、自動的に無効化される。

If you want to ensure that devtools is never included in a production build, you can use the excludeDevtools build property to completely remove the JAR. The property is supported with both the Maven and Gradle plugins.

リリース用のJarなどにdevtoolを含めたくない場合、build propertyのexcludeDevtools でremoveすることができる。(maven,gradleともに対応可能)

20.1 Property defaults

Several of the libraries supported by Spring Boot use caches to improve performance. For example, Thymeleaf will cache templates to save repeatedly parsing XML source files. Whilst caching is very beneficial in production, it can be counter productive during development. If you make a change to a template file in your IDE, you’ll likely want to immediately see the result.

Cache options are usually configured by settings in your application.properties file. For example, Thymeleaf offers the spring.thymeleaf.cache property. Rather than needing to set these properties manually, the spring-boot-devtools module will automatically apply sensible development-time configuration.

Spring Bootのライブラリはキャッシュ機構を備えているが、開発時には邪魔になるので、spring-boot-devtools moduleが動作する場合、いくつかのキャッシュ機構は自動的に無効になる。
具体的に何が無効になるのか知りたい場合は、下記を参照
DevToolsPropertyDefaultsPostProcessor.

20.2 Automatic restart

Applications that use spring-boot-devtools will automatically restart whenever files on the classpath change. This can be a useful feature when working in an IDE as it gives a very fast feedback loop for code changes. By default, any entry on the classpath that points to a folder will be monitored for changes. Note that certain resources such as static assets and view templates do not need to restart the application.

アプリケーションがspring-boot-devtoolsを使っている場合、classpathのファイルの変更を検知し自動的にrestartします。
静的なファイルやtemplateなどの変更では自動再起動する必要はありません。

#編集注記:静的ファイルは、除外設定してねという事だと思う。

Triggering a restart
As DevTools monitors classpath resources, the only way to trigger a restart is to update the classpath. The way in which you cause the classpath to be updated depends on the IDE that you are using. In Eclipse, saving a modified file will cause the classpath to be updated and trigger a restart. In IntelliJ IDEA, building the project (Build → Make Project) will have the same effect.

アプリケーション再起動のトリガー

  • Eclipseの場合、ファイルを変更して保存したタイミング
  • IntelliJ IDEAの場合、Build -> Make Projectしたタイミング

DevTools relies on the application context’s shutdown hook to close it during a restart. It will not work correctly if you have disabled the shutdown hook

DevTools はアプリケーションコンテキストのShutdownをフックに依存している。
アプリケーションがシャットダウンフックを無効にしているとDevTools は正常に動作しない。

20.2.1 Excluding resources

Certain resources don’t necessarily need to trigger a restart when they are changed. For example, Thymeleaf templates can just be edited in-place. By default changing resources in /META-INF/maven, /META-INF/resources ,/resources ,/static ,/public or /templates will not trigger a restart but will trigger a live reload. If you want to customize these exclusions you can use the spring.devtools.restart.exclude property. For example, to exclude only /static and /public you would set the following:

spring.devtools.restart.exclude=static/**,public/**

Automatic restartの対象から除外したいファイルがある場合、application.propertiesに上記のように設定する。

if you want to keep those defaults and add additional exclusions, use the spring.devtools.restart.additional-exclude property instead.

spring.devtools.restart.exclude=static/**,public/**

デフォルトの設定に追加したい場合、上記のように記載する選択肢もある。

20.2.2 Watching additional paths

You may want your application to be restarted or reloaded when you make changes to files that are not on the classpath. To do so, use the spring.devtools.restart.additional-paths property to configure additional paths to watch for changes. You can use the spring.devtools.restart.exclude property described above to control whether changes beneath the additional paths will trigger a full restart or just a live reload.

automatic restartの監視対象パスを増やしたい場合、spring.devtools.restart.additional-paths propertieに設定すればよい。

20.2.3 Disabling restart

If you don’t want to use the restart feature you can disable it using the spring.devtools.restart.enabled property. In most cases you can set this in your application.properties (this will still initialize the restart classloader but it won’t watch for file changes).

DevToolのauto restartを無効化したい場合、spring.devtools.restart.enabledプロパティが使用できる。
通常はapplication.propertiesに設定すれば事足りるが完璧に無効化したい場合は、Sampleのようにmain()メソッドでSpringApplication.run()する前にSystemプロパティに設定する方法もある。

20.3 LiveReload

The spring-boot-devtools module includes an embedded LiveReload server that can be used to trigger a browser refresh when a resource is changed. LiveReload browser extensions are freely available for Chrome, Firefox and Safari from livereload.com.

spring-boot-devtoolsのLiveReload機能はリソースの変更時にブラウザのリロードをトリガーする。
LiveReload Browser ExtentionはChrome,Firefox,Safari用が無料配布されている。

#編集注記:LiveReloadを使用するにはあらかじめブラウザにExtentionを入れておく必要があるってことかな

20.4 Global settings

You can configure global devtools settings by adding a file named .spring-boot-devtools.properties to your $HOME folder (note that the filename starts with “.”). Any properties added to this file will apply to all Spring Boot applications on your machine that use devtools. For example, to configure restart to always use a trigger file, you would add the following:

グローバル設定は$HOME配下の.spring-boot-devtools.propertiesに設定することができる。

20.5 Remote applications

The Spring Boot developer tools are not just limited to local development. You can also use several features when running applications remotely. Remote support is opt-in, to enable it you need to set a spring.devtools.remote.secret property.

DevToolはリモートで動作しているアプリケーションに対しても有効。
リモートアプリケーションでDevToolを使う場合spring.devtools.remote.secret
の設定が必要。

#編集注記:設定値はなんでもいいようです。

Remote devtools support is provided in two parts; there is a server side endpoint that accepts connections, and a client application that you run in your IDE. The server component is automatically enabled when the >spring.devtools.remote.secret property is set. The client component must be launched manually.

Remote DevToolは2つのパーツで構成されている。
サーバーサイドとクライアント(IDE).spring.devtools.remote.secretプロパティを設定すればサーバーサイドは自動的にRemote Devtoolが有効になる。
クライアント(IDE)側は手動で起動する必要がある。

20.5.1 Running the remote client application

The remote client application is designed to be run from within you IDE. You need to run org.springframework.boot.devtools.RemoteSpringApplication using the same classpath as the remote project that you’re connecting to. The non-option argument passed to the application should be the remote URL that you are connecting to.

Remote DevToolを使うには
リモートクライアント(IDE)側では、アプリケーション(オプション以外の引数)に接続先のリモートURLを渡します。次に実行時のmainクラスにorg.springframework.boot.devtools.RemoteSpringApplication
を指定します。
これだけ。

20.5.2 Remote update

Java remote debugging is useful when diagnosing issues on a remote application. Unfortunately, it’s not always possible to enable remote debugging when your application is deployed outside of your data center. Remote debugging can also be tricky to setup if you are using a container based technology such as Docker.

リモートデバッグは有効な手段ですが、環境によっては必ず実行できるとは限りません。
例えばDockerとか注意が必要です。

21. Packaging your application for production

Executable jars can be used for production deployment. As they are self-contained, they are also ideally suited for cloud-based deployment.

実行形式のjarを本番リリース用として使えます。
これはクラウドベースへの展開へ適していますよ。

Part IV. Spring Boot features

このセクションではSpring Bootの詳細について説明します。

23. SpringApplication

The SpringApplication class provides a convenient way to bootstrap a Spring application that will be started from a main() method. In many situations you can just delegate to the static SpringApplication.run method:

SpringApplicationクラスはSpringApplicationを起動するための便利な機能を実装しています。
main()メソッドでSpringApplication.runを実行するだけ。

23.1 Customizing the Banner

The banner that is printed on start up can be changed by adding a banner.txt file to your classpath, or by setting banner.location to the location of such a file. If the file has an unusual encoding you can set banner.charset (default is UTF-8).

起動時のバナーは変更する事が出来ます。
banner.txt、banner.location、banner.charsetなどでカスタマイズできます。

Table 23.1. Banner variables

バナーで使える環境変数はTable 23.1.を参照

23.2 Customizing SpringApplication

If the SpringApplication defaults aren’t to your taste you can instead create a local instance and customize it. For example, to turn off the banner you would write:

SpringApplication のデフォルトが気に入らなければ、SpringApplicationのインスタンスを生成してオプションを設定する事が出来ます。

例えば、こんな感じ
java
public static void main(String[] args) {
SpringApplication app = new SpringApplication(MySpringConfiguration.class);
app.setBannerMode(Banner.Mode.OFF);
app.run(args);
}

23.4 Application events and listeners

In addition to the usual Spring Framework events, such as ContextRefreshedEvent, a SpringApplication sends some additional application events.

SpringApplication.addListeners(…​)に設定しておけば、Spring frameworkのイベントを受けることができる。

以降、また時間のあるときに。。

6
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
9