---
title: Spring Bootの組み込みTomcatでHTTPS対応 springboot
tags: ["Java", "Spring", "Spring Boot"]
categories: ["Programming", "Java", "org", "springframework", "boot", "context", "embedded"]
date: 2014-06-12T05:40:53Z
updated: 2014-06-12T05:40:53Z
---

Spring Bootの組み込みTomcatでHTTPSに対応する方法メモ。

まずはHello Worldプロジェクトを作る。手順は[これ](/#/entries/265)と同じ。

### App.java修正

`App.java`にちょっと追記。次に説明する`AppConfig.java`の設定を自動で読み込むために`@ComponentScan`を追加する。

    package com.example;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    @EnableAutoConfiguration
    @ComponentScan // ここ追加
    public class App {
    
        @RequestMapping("/")
        String home() {
            return "Hello World!";
        }
    
    
        public static void main(String[] args) {
            SpringApplication.run(App.class, args);
        }
    }

### JavaConfig作成

次にBean定義JavaConfig作成。


    package com.example;
    
    import org.apache.coyote.http11.Http11NioProtocol;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory;
    import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.util.ResourceUtils;
    
    import java.io.FileNotFoundException;
    
    @Configuration
    public class AppConfig {
        @Value("${keystore.file:keystore.p12}")
        String keystoreFile;
        @Value("${keystore.password:foobar}")
        String keystorePassword;
    
        @Bean
        public EmbeddedServletContainerFactory servletContainer() throws FileNotFoundException {
            TomcatEmbeddedServletContainerFactory factory = new TomcatEmbeddedServletContainerFactory();
            String absoluteKeystoreFile = ResourceUtils.getFile(keystoreFile).getAbsolutePath();
    
            factory.addConnectorCustomizers((connector) -> {
                connector.setPort(8443);
                connector.setSecure(true);
                connector.setScheme("https");
                Http11NioProtocol proto = (Http11NioProtocol) connector.getProtocolHandler();
                proto.setSSLEnabled(true);
                proto.setKeystoreFile(absoluteKeystoreFile);
                proto.setKeystorePass(keystorePassword);
                proto.setKeystoreType("PKCS12");
                proto.setKeyAlias("tomcat");
            });
            return factory;
        }
    }

組み込みコンテナの変更方法は[ここ](http://docs.spring.io/spring-boot/docs/1.1.1.RELEASE/reference/htmlsingle/#boot-features-customizing-configurableembeddedservletcontainerfactory-directly)を参考にした。

### Keystore

    $ keytool -genkey -alias tomcat -storetype PKCS12 -keyalg RSA -keysize 2048 -keystore keystore.p12 -validity 3650

パスワードはJavaConfigの通り、foobarにした。

### 実行

    (途中略)
    2014-06-12 23:58:45.869  INFO 4150 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8443/https
    2014-06-12 23:58:45.872  INFO 4150 --- [           main] com.example.App                          : Started App in 5.605 seconds (JVM running for 6.435)

8443番でHTTPSが！

https://localhost:8443 にアクセス。

![image](https://qiita-image-store.s3.amazonaws.com/0/1852/d88589de-df06-99b2-6007-e0b1cb90c1ed.png)

できた！

### 設定値を外から変更

ビルドして実行可能jarにした後、`--プロパティ名`で`@Value`で設定したプロパティを変更可能。（システムプロパティや環境変数でもOKなはず）

    $ mvn package
    $ java -jar target/hajiboot-1.0.0-SNAPSHOT.jar --keystore.password=hoge

----
この[サンプル](https://github.com/joshlong/spring-boot-embedded-tomcat-ssl)を参考にしました。

**2014-06-23追記**
[本家ドキュメント](http://docs.spring.io/spring-boot/docs/1.1.1.RELEASE/reference/html/howto-embedded-servlet-containers.html#howto-terminate-ssl-in-tomcat)に書いてあった・・
