SpringとSpring Bootの比較
1. 概要
この記事では、標準のSpringフレームワークとSpringBootの違いを見ていきます。
ここでは、MVCやセキュリティなどのSpringのモジュールが、コアSpringで使用した場合とBootで使用した場合の違いに焦点を当てて説明します。
参考文献:
2. 春とは?
Simply put, the Spring framework provides comprehensive infrastructure support for developing Java applications。
依存性注入などの優れた機能と、次のようなすぐに使用できるモジュールが満載です。
-
Spring JDBC
-
春MVC
-
春のセキュリティ
-
春のAOP
-
春のORM
-
ばね試験
これらのモジュールは、アプリケーションの開発時間を大幅に短縮できます。
たとえば、Java Web開発の初期には、データソースにレコードを挿入するための定型コードを大量に記述する必要がありました。 ただし、Spring JDBCモジュールのJDBCTemplateを使用することで、わずかな構成で数行のコードに減らすことができます。
3. Spring Bootとは何ですか?
Spring Bootは基本的にSpringフレームワークの拡張であり、Springアプリケーションの設定に必要な定型的な構成を排除します。
It takes an opinionated view of the Spring platform which paved the way for a faster and more efficient development eco-system。
Spring Bootの機能のほんの一部を次に示します。
-
ビルドとアプリケーションの構成を簡素化するための「スターター」依存関係の意見
-
アプリケーション展開の複雑さを回避する組み込みサーバー
-
メトリックス、ヘルスチェック、外部化された構成
-
Spring機能の自動構成-可能な限り
これらのフレームワークの両方を段階的に理解していきましょう。
4. Mavenの依存関係
まず、Springを使用してWebアプリケーションを作成するために必要な最小限の依存関係を見てみましょう。
org.springframework
spring-web
5.1.0.RELEASE
org.springframework
spring-webmvc
5.1.0.RELEASE
Springとは異なり、Spring BootはWebアプリケーションを起動して実行するために1つの依存関係のみを必要とします。
org.springframework.boot
spring-boot-starter-web
2.0.5.RELEASE
他のすべての依存関係は、ビルド時に最終アーカイブに自動的に追加されます。
別の良い例は、ライブラリのテストです。 通常、Spring Test、JUnit、Hamcrest、Mockitoライブラリのセットを使用します。 Springプロジェクトでは、これらすべてのライブラリを依存関係として追加する必要があります。
しかし、Spring Bootでは、これらのライブラリを自動的にインクルードするためのテストのスターター依存関係のみが必要です。
Spring Boot provides a number of starter dependencies for different Spring modules.最も一般的に使用されるもののいくつかは次のとおりです。
-
spring-boot-starter-data-jpa
-
spring-boot-starter-security
-
spring-boot-starter-test
-
spring-boot-starter-web
-
spring-boot-starter-thymeleaf
スターターの完全なリストについては、Spring documentationも確認してください。
5. MVC構成
SpringとSpringBootの両方を使用してJSPWebアプリケーションを作成するために必要な構成を調べてみましょう。
Spring requires defining the dispatcher servlet, mappings, and other supporting configurations.これは、web.xmlファイルまたはInitializerクラスのいずれかを使用して実行できます。
public class MyWebAppInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext container) {
AnnotationConfigWebApplicationContext context
= new AnnotationConfigWebApplicationContext();
context.setConfigLocation("com.example");
container.addListener(new ContextLoaderListener(context));
ServletRegistration.Dynamic dispatcher = container
.addServlet("dispatcher", new DispatcherServlet(context));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
}
}
また、@EnableWebMvcアノテーションを@Configurationクラスに追加し、コントローラーから返されたビューを解決するためのビューリゾルバーを定義する必要があります。
@EnableWebMvc
@Configuration
public class ClientWebConfig implements WebMvcConfigurer {
@Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver bean
= new InternalResourceViewResolver();
bean.setViewClass(JstlView.class);
bean.setPrefix("/WEB-INF/view/");
bean.setSuffix(".jsp");
return bean;
}
}
これらすべてと比較すると、Spring Boot only needs a couple of properties to make things work, once we’ve added the web starter:
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
上記のすべてのSpring構成は、auto-configurationと呼ばれるプロセスを通じて、BootWebスターターを追加することによって自動的に含まれます。
つまり、Spring Bootは、アプリケーションに存在する依存関係、プロパティ、およびBeanを調べ、これらに基づいて構成を有効にします。
もちろん、独自のカスタム構成を追加する場合、Spring Bootの自動構成は元に戻ります。
5.1. テンプレートエンジンの構成
ここで、SpringとSpring Bootの両方でThymeleafテンプレートエンジンを構成する方法を学びましょう。
Springでは、thymeleaf-spring5の依存関係とビューリゾルバーのいくつかの構成を追加する必要があります。
@Configuration
@EnableWebMvc
public class MvcWebConfig implements WebMvcConfigurer {
@Autowired
private ApplicationContext applicationContext;
@Bean
public SpringResourceTemplateResolver templateResolver() {
SpringResourceTemplateResolver templateResolver =
new SpringResourceTemplateResolver();
templateResolver.setApplicationContext(applicationContext);
templateResolver.setPrefix("/WEB-INF/views/");
templateResolver.setSuffix(".html");
return templateResolver;
}
@Bean
public SpringTemplateEngine templateEngine() {
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver());
templateEngine.setEnableSpringELCompiler(true);
return templateEngine;
}
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
ThymeleafViewResolver resolver = new ThymeleafViewResolver();
resolver.setTemplateEngine(templateEngine());
registry.viewResolver(resolver);
}
}
Spring Boot 1では、WebアプリケーションでThymeleafのサポートを有効にするために、spring-boot-starter-thymeleaf の依存関係のみが必要でした。 ただし、Thymeleaf3.0, の新機能のため、Spring Boot 2 Webアプリケーションの依存関係としてthymeleaf-layout-dialect も追加する必要があります。
依存関係が設定されたら、テンプレートをsrc/main/resources/templatesフォルダーに追加すると、SpringBootによってテンプレートが自動的に表示されます。
6. Spring Securityの構成
簡単にするために、これらのフレームワークを使用してデフォルトのHTTP基本認証がどのように有効化されるかを見ていきます。
まず、Springを使用してセキュリティを有効にするために必要な依存関係と構成を見てみましょう。
Spring requires both the standard the spring-security-web and spring-security-config dependenciesを使用して、アプリケーションにセキュリティを設定します。
次に、we need to add a class that extends the WebSecurityConfigurerAdapter and makes use of the @EnableWebSecurityアノテーション:
@Configuration
@EnableWebSecurity
public class CustomWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user1")
.password(passwordEncoder()
.encode("user1Pass"))
.authorities("ROLE_USER");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest().authenticated()
.and()
.httpBasic();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
ここでは、inMemoryAuthenticationを使用して認証を設定しています。
同様に、Spring Bootを機能させるにはこれらの依存関係も必要です。 ただし、spring-boot-starter-security as this will automatically add all the relevant dependencies to the classpath.の依存関係のみを定義する必要があります
SpringBootのセキュリティ構成は上記と同じです。
SpringとSpringBootの両方でJPA構成を実現する方法を知る必要がある場合は、記事A Guide to JPA with Springを確認してください。
7. アプリケーションのブートストラップ
SpringとSpring Bootでのアプリケーションのブートストラップの基本的な違いは、サーブレットにあります。 Springは、ブートストラップエントリポイントとしてweb.xmlまたはSpringServletContainerInitializer のいずれかを使用します。
一方、Spring Bootはサーブレット3の機能のみを使用してアプリケーションをブートストラップします。 これについて詳しく説明しましょう。
7.1. どのように春のブートストラップ?
Springは、従来のweb.xmlのブートストラップ方法と、最新のサーブレット3+メソッドの両方をサポートしています。
web.xmlのアプローチを段階的に見てみましょう。
-
サーブレットコンテナ(サーバー)はweb.xmlを読み取ります
-
web.xmlで定義されたDispatcherServletは、コンテナによってインスタンス化されます
-
DispatcherServletはWEB-INF/{servletName}-servlet.xmlを読み込むことでWebApplicationContextを作成する。
-
最後に、DispatcherServletは、アプリケーションコンテキストで定義されたBeanを登録します
サーブレット3以降のアプローチを使用してSpringがブートストラップする方法は次のとおりです。
-
コンテナはServletContainerInitializer を実装するクラスを検索し、実行します
-
SpringServletContainerInitializerは、WebApplicationInitializerを実装するすべてのクラスを検索します
-
WebApplicationInitializerは、XMLまたは@Configurationクラスでコンテキストを作成します
-
WebApplicationInitializerは、以前に作成されたコンテキストでDispatcherServlet を作成します。
7.2. どのようにSpringBootブートストラップ?
Spring Bootアプリケーションのエントリポイントは、@SpringBootApplicationで注釈が付けられたクラスです。
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
デフォルトでは、Spring Bootは埋め込みコンテナを使用してアプリケーションを実行します。 この場合、Spring Bootはpublic static void mainエントリポイントを使用して組み込みWebサーバーを起動します。
また、アプリケーションコンテキストから埋め込みサーブレットコンテナへのServlet, Filter,およびServletContextInitializerBeanのバインドも処理します。
Spring Bootのもう1つの機能は、コンポーネントのメインパッケージの同じパッケージまたはサブパッケージ内のすべてのクラスを自動的にスキャンすることです。
Spring Bootには、外部コンテナーにWebアーカイブとして展開するオプションもあります。 この場合、SpringBootServletInitializerを拡張する必要があります。
@SpringBootApplication
public class Application extends SpringBootServletInitializer {
// ...
}
ここで、外部サーブレットコンテナはWebアーカイブのMETA-INFファイルで定義されたメインクラスを検索し、SpringBootServletInitializerがServlet, Filter,とServletContextInitializer.のバインドを処理します。
8. パッケージングと展開
最後に、アプリケーションをパッケージ化してデプロイする方法を見てみましょう。 これらのフレームワークはどちらも、MavenやGradleなどの一般的なパッケージ管理テクノロジーをサポートしています。 しかし、展開に関しては、これらのフレームワークは大きく異なります。
たとえば、Spring Boot Maven PluginはMavenでSpringBootのサポートを提供します。 また、実行可能jarまたはwarアーカイブをパッケージ化し、「インプレース」でアプリケーションを実行できます。
デプロイメントのコンテキストにおけるSpringに対するSpring Bootの利点には、次のものがあります。
-
埋め込みコンテナのサポートを提供します
-
コマンドjava -jarを使用してjarを個別に実行するようにプロビジョニングします
-
外部コンテナーにデプロイするときに潜在的なjarの競合を回避するために依存関係を除外するオプション
-
展開時にアクティブなプロファイルを指定するオプション
-
統合テスト用のランダムポート生成
9. 結論
このチュートリアルでは、SpringとSpringBootの違いについて学びました。
簡単に言えば、Spring Bootは、開発、テスト、展開をより便利にするためのSpring自体の単なる拡張であると言えます。