经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » Java相关 » Java » 查看文章
为什么使用 Spring Boot?
来源:cnblogs  作者:手留余香·  时间:2018/11/3 10:07:58  对本文有异议

Spring 是一个非常流行的基于Java语言的开发框架,此框架用来构建web和企业应用程序。与许多其他仅关注一个领域的框架不同,Spring框架提供了广泛的功能,通过其组合项目满足现代业务需求。

Spring框架提供了以多种方式配置bean的灵活性,例如XML,注解和JavaConfig。随着功能数量的增加,复杂性也会增加,配置Spring应用程序变得乏味且容易出错。

Spring团队创建了Spring Boot来解决配置的复杂性。

但在深入了解SpringBoot之前,我们将快速浏览一下Spring框架,看看SpringBoot试图解决的问题是什么。

在本文中,我们将介绍:

  • Spring框架概述
  • 使用Spring MVC和JPA(Hibernate)的Web应用
  • 快速试用SpringBoot

Spring 框架概述

如果你是 Java 开发人员,那么你多半听说过 Spring 框架,甚至可能在项目中使用过这一框架。Spring 框架主要起源于一个依赖注入容器,但它远不止于此。

Spring 之所以流行,是因为:

  • Spring 的依赖注入方法支持编写可测试的代码
  • 强大且易用的数据库事务管理能力
  • Spring 非常容易与其它 Java 框架集成,如 JPA/Hibernate ORM、Struts、JSF等。
  • 使用前沿的 MVC 框架构建 Web 应用

Spring 除了框架之外,还有很多姊妹项目可以助力构建满足现代业务需求的应用程序:

  • Spring Data:为访问关系型数据库或 NoSQL 数据库提供便利。
  • Spring Batch:强大的批处理框架。
  • Spring Security:为安全应用而生的强健的安全框架。
  • Spring Social:支持整合社区网络,比如 Facebook、Twitter、LinkedIn、Github 等。
  • Spring Integration:企业级集成模型的实现,使用轻量级的消息传递和声明式适配器与其他企业应用集成。

还有不少其他有趣的项目,他们用于解决各种现代应用开发需求。欲知详情,请看 http://spring.io/projects。

Spring 框架一开始提供了基于 XML 的方法来配置 Bean。之后 Spring 引入了基于 XML 的 DSL、注解和 JavaConfig 来配置 Bean 的方法。

让我们快速看看每种配置方式的样子。

基于XML的配置

 

 
图0:为什么使用 Spring Boot?

 

基于注释的配置

 

 
图1:为什么使用 Spring Boot?

 

基于JavaConfig的配置

 

 
图2:为什么使用 Spring Boot?

 

哇… Spring提供了很多方法来做同样的事情,我们甚至可以混合使用这些方法,并在同一个应用程序中同时使用基于JavaConfig和注解的配置方式。

但是没有一种适合所有类型的解决方案。必须根据自己的应用需求选择方法。

好了,现在您已经看到了各种样式的Spring bean配置的例子。

让我们快速浏览一下典型的SpringMVC + JPA / Hibernate Web应用程序配置的样子。

使用Spring MVC和JPA(Hibernate)的Web应用程序

在了解SpringBoot是什么以及提供了什么样的功能之前,让我们先看看典型的Spring Web应用程序配置如何,难点又是什么,其次我们论述SpringBoot将如何解决这些问题。

第1步:配置Maven依赖项

首要的是我们需要配置pom.xml中所需的所有依赖项。

  1. <?xml version="1.0" encoding="UTF-8"?>
  2.  
  3. <project xmlns="http://maven.apache.org/POM/4.0.0"
  4.  
  5. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  6.  
  7. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
  8.  
  9. http://maven.apache.org/maven-v4_0_0.xsd">
  10.  
  11. <modelVersion>4.0.0</modelVersion>
  12.  
  13. <groupId>com.sivalabs</groupId>
  14.  
  15. <artifactId>springmvc-jpa-demo</artifactId>
  16.  
  17. <packaging>war</packaging>
  18.  
  19. <version>1.0-SNAPSHOT</version>
  20.  
  21. <name>springmvc-jpa-demo</name>
  22.  
  23.  
  24. <properties>
  25.  
  26. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  27.  
  28. <maven.compiler.source>1.8</maven.compiler.source>
  29.  
  30. <maven.compiler.target>1.8</maven.compiler.target>
  31.  
  32. <failOnMissingWebXml>false</failOnMissingWebXml>
  33.  
  34. </properties>
  35.  
  36.  
  37. <dependencies>
  38.  
  39. <dependency>
  40.  
  41. <groupId>org.springframework</groupId>
  42.  
  43. <artifactId>spring-webmvc</artifactId>
  44.  
  45. <version>4.2.4.RELEASE</version>
  46.  
  47. </dependency>
  48.  
  49. <dependency>
  50.  
  51. <groupId>org.springframework.data</groupId>
  52.  
  53. <artifactId>spring-data-jpa</artifactId>
  54.  
  55. <version>1.9.2.RELEASE</version>
  56.  
  57. </dependency>
  58.  
  59. <dependency>
  60.  
  61. <groupId>org.slf4j</groupId>
  62.  
  63. <artifactId>jcl-over-slf4j</artifactId>
  64.  
  65. <version>1.7.13</version>
  66.  
  67. </dependency>
  68.  
  69. <dependency>
  70.  
  71. <groupId>org.slf4j</groupId>
  72.  
  73. <artifactId>slf4j-api</artifactId>
  74.  
  75. <version>1.7.13</version>
  76.  
  77. </dependency>
  78.  
  79. <dependency>
  80.  
  81. <groupId>org.slf4j</groupId>
  82.  
  83. <artifactId>slf4j-log4j12</artifactId>
  84.  
  85. <version>1.7.13</version>
  86.  
  87. </dependency>
  88.  
  89. <dependency>
  90.  
  91. <groupId>log4j</groupId>
  92.  
  93. <artifactId>log4j</artifactId>
  94.  
  95. <version>1.2.17</version>
  96.  
  97. </dependency>
  98.  
  99. <dependency>
  100.  
  101. <groupId>com.h2database</groupId>
  102.  
  103. <artifactId>h2</artifactId>
  104.  
  105. <version>1.4.190</version>
  106.  
  107. </dependency>
  108.  
  109. <dependency>
  110.  
  111. <groupId>commons-dbcp</groupId>
  112.  
  113. <artifactId>commons-dbcp</artifactId>
  114.  
  115. <version>1.4</version>
  116.  
  117. </dependency>
  118.  
  119. <dependency>
  120.  
  121. <groupId>mysql</groupId>
  122.  
  123. <artifactId>mysql-connector-java</artifactId>
  124.  
  125. <version>5.1.38</version>
  126.  
  127. </dependency>
  128.  
  129. <dependency>
  130.  
  131. <groupId>org.hibernate</groupId>
  132.  
  133. <artifactId>hibernate-entitymanager</artifactId>
  134.  
  135. <version>4.3.11.Final</version>
  136.  
  137. </dependency>
  138.  
  139. <dependency>
  140.  
  141. <groupId>javax.servlet</groupId>
  142.  
  143. <artifactId>javax.servlet-api</artifactId>
  144.  
  145. <version>3.1.0</version>
  146.  
  147. <scope>provided</scope>
  148.  
  149. </dependency>
  150.  
  151. <dependency>
  152.  
  153. <groupId>org.thymeleaf</groupId>
  154.  
  155. <artifactId>thymeleaf-spring4</artifactId>
  156.  
  157. <version>2.1.4.RELEASE</version>
  158.  
  159. </dependency>
  160.  
  161. </dependencies>
  162.  
  163. </project>

  

我们已经配置好了所有Maven jar依赖项,包括Spring MVC,Spring Data JPA,JPA / Hibernate,Thymeleaf和Log4j。

第 2 步:使用 JavaConfig 配置 Service/DAO 层的 Bean

  1. @Configuration
  2.  
  3. @EnableTransactionManagement
  4.  
  5. @EnableJpaRepositories(basePackages="com.sivalabs.demo")
  6.  
  7. @PropertySource(value = { "classpath:application.properties" })
  8.  
  9. public class AppConfig
  10.  
  11. {
  12.  
  13. @Autowired
  14.  
  15. private Environment env;
  16.  
  17.  
  18. @Bean
  19.  
  20. public static PropertySourcesPlaceholderConfigurer placeHolderConfigurer()
  21.  
  22. {
  23.  
  24. return new PropertySourcesPlaceholderConfigurer();
  25.  
  26. }
  27.  
  28.  
  29. @Value("${init-db:false}")
  30.  
  31. private String initDatabase;
  32.  
  33.  
  34. @Bean
  35.  
  36. public PlatformTransactionManager transactionManager()
  37.  
  38. {
  39.  
  40. EntityManagerFactory factory = entityManagerFactory().getObject();
  41.  
  42. return new JpaTransactionManager(factory);
  43.  
  44. }
  45.  
  46.  
  47. @Bean
  48.  
  49. public LocalContainerEntityManagerFactoryBean entityManagerFactory()
  50.  
  51. {
  52.  
  53. LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
  54.  
  55.  
  56. HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
  57.  
  58. vendorAdapter.setGenerateDdl(Boolean.TRUE);
  59.  
  60. vendorAdapter.setShowSql(Boolean.TRUE);
  61.  
  62.  
  63. factory.setDataSource(dataSource());
  64.  
  65. factory.setJpaVendorAdapter(vendorAdapter);
  66.  
  67. factory.setPackagesToScan("com.sivalabs.demo");
  68.  
  69.  
  70. Properties jpaProperties = new Properties();
  71.  
  72. jpaProperties.put("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
  73.  
  74. factory.setJpaProperties(jpaProperties);
  75.  
  76.  
  77. factory.afterPropertiesSet();
  78.  
  79. factory.setLoadTimeWeaver(new InstrumentationLoadTimeWeaver());
  80.  
  81. return factory;
  82.  
  83. }
  84.  
  85.  
  86. @Bean
  87.  
  88. public HibernateExceptionTranslator hibernateExceptionTranslator()
  89.  
  90. {
  91.  
  92. return new HibernateExceptionTranslator();
  93.  
  94. }
  95.  
  96.  
  97. @Bean
  98.  
  99. public DataSource dataSource()
  100.  
  101. {
  102.  
  103. BasicDataSource dataSource = new BasicDataSource();
  104.  
  105. dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
  106.  
  107. dataSource.setUrl(env.getProperty("jdbc.url"));
  108.  
  109. dataSource.setUsername(env.getProperty("jdbc.username"));
  110.  
  111. dataSource.setPassword(env.getProperty("jdbc.password"));
  112.  
  113. return dataSource;
  114.  
  115. }
  116.  
  117.  
  118. @Bean
  119.  
  120. public DataSourceInitializer dataSourceInitializer(DataSource dataSource)
  121.  
  122. {
  123.  
  124. DataSourceInitializer dataSourceInitializer = new DataSourceInitializer();
  125.  
  126. dataSourceInitializer.setDataSource(dataSource);
  127.  
  128. ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator();
  129.  
  130. databasePopulator.addScript(new ClassPathResource("data.sql"));
  131.  
  132. dataSourceInitializer.setDatabasePopulator(databasePopulator);
  133.  
  134. dataSourceInitializer.setEnabled(Boolean.parseBoolean(initDatabase));
  135.  
  136. return dataSourceInitializer;
  137.  
  138. }
  139.  
  140. }

  

在 AppConfig.java 所描述的配置类中,我们做了下面的事情:

  • 使用 @Configuration 注解使之成为 Spring 配置类。
  • 使用 @EnableTransactionManagement 注解允许基于注解的事务管理。
  • 配置 @EnableJpaRepositories 指示在哪里寻找 Spring Data JPA 库。
  • Configured PropertyPlaceHolder bean u使用 @PropertySource 注解和 PropertySourcesPlaceholderConfigurer 定义来配置 PropertyPlaceHolder Bean。配置属性来自 application.properties 文件。
  • 为 DataSource、JPA EntityManagerFactory 和 JpaTransactionManager 定义 Bean。
  • 配置 DataSourceInitializer Bean,使之在应用启动时执行 data.sql 脚本,初始化数据库。

我们需要在 application.properties 中配置占位属性值:

 

 
图3:为什么使用 Spring Boot?

 

创建简单的 SQL 脚本,data.sql,将示例数据填入 USER 表中:

 

 
图4:为什么使用 Spring Boot?

 

创建 log4j.properties 文件,在其中写一些基础配置:

 

 
图5:为什么使用 Spring Boot?

 

 

第3步:配置Spring MVC Web层Beans

我们必须配置Thymeleaf ViewResolver,静态ResourceHandlers,适用于国际化的MessageSource,等等。

  1. @Configuration
  2.  
  3. @ComponentScan(basePackages = { "com.sivalabs.demo"})
  4.  
  5. @EnableWebMvc
  6.  
  7. public class WebMvcConfig extends WebMvcConfigurerAdapter
  8.  
  9. {
  10.  
  11. @Bean
  12.  
  13. public TemplateResolver templateResolver() {
  14.  
  15. TemplateResolver templateResolver = new ServletContextTemplateResolver();
  16.  
  17. templateResolver.setPrefix("/WEB-INF/views/");
  18.  
  19. templateResolver.setSuffix(".html");
  20.  
  21. templateResolver.setTemplateMode("HTML5");
  22.  
  23. templateResolver.setCacheable(false);
  24.  
  25. return templateResolver;
  26.  
  27. }
  28.  
  29.  
  30. @Bean
  31.  
  32. public SpringTemplateEngine templateEngine() {
  33.  
  34. SpringTemplateEngine templateEngine = new SpringTemplateEngine();
  35.  
  36. templateEngine.setTemplateResolver(templateResolver());
  37.  
  38. return templateEngine;
  39.  
  40. }
  41.  
  42.  
  43. @Bean
  44.  
  45. public ThymeleafViewResolver viewResolver() {
  46.  
  47. ThymeleafViewResolver thymeleafViewResolver = new ThymeleafViewResolver();
  48.  
  49. thymeleafViewResolver.setTemplateEngine(templateEngine());
  50.  
  51. thymeleafViewResolver.setCharacterEncoding("UTF-8");
  52.  
  53. return thymeleafViewResolver;
  54.  
  55. }
  56.  
  57.  
  58. @Override
  59.  
  60. public void addResourceHandlers(ResourceHandlerRegistry registry)
  61.  
  62. {
  63.  
  64. registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
  65.  
  66. }
  67.  
  68.  
  69. @Override
  70.  
  71. public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer)
  72.  
  73. {
  74.  
  75. configurer.enable();
  76.  
  77. }
  78.  
  79.  
  80. @Bean(name = "messageSource")
  81.  
  82. public MessageSource configureMessageSource()
  83.  
  84. {
  85.  
  86. ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
  87.  
  88. messageSource.setBasename("classpath:messages");
  89.  
  90. messageSource.setCacheSeconds(5);
  91.  
  92. messageSource.setDefaultEncoding("UTF-8");
  93.  
  94. return messageSource;
  95.  
  96. }
  97.  
  98. }

  

在我们的WebMvcConfig.java配置类中我们完成以下操作:

  • 使用@Configuration注解将其标记为Spring配置类。
  • 使用@EnableWebMvc启用基于注解的Spring MVC配置,
  • 通过注册TemplateResolverSpringTemplateEngineThymeleafViewResolver Bean来配置Thymeleaf ViewResolver。
  • 注册ResourceHandlers Bean表明URI/resources/**静态资源请求将由本地/resources/目录提供服务。
  • 配置MessageSource Bean通过ResourceBundle加载classpath下的messages-{country-code}.properties国际化信息。

目前我们没有要配置的信息,所以在src/main/resources文件夹下创建一个空的messages.properties文件。

第4步:注册Spring MVC FrontController Servlet DispatcherServlet

在Servlet 3.x规范之前我们必须在web.xml注册Servlets/Filters。自从Servlet 3.x规范出台我们能够使用ServletContainerInitializer以编程方式注册Servlets/Filters。

Spring MVC提供了一个方便的类AbstractAnnotationConfigDispatcherServletInitializer用于注册DispatcherServlet.

  1. public class SpringWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer
  2.  
  3. {
  4.  
  5.  
  6. @Override
  7.  
  8. protected Class<?>[] getRootConfigClasses()
  9.  
  10. {
  11.  
  12. return new Class<?>[] { AppConfig.class};
  13.  
  14. }
  15.  
  16.  
  17. @Override
  18.  
  19. protected Class<?>[] getServletConfigClasses()
  20.  
  21. {
  22.  
  23. return new Class<?>[] { WebMvcConfig.class };
  24.  
  25. }
  26.  
  27.  
  28. @Override
  29.  
  30. protected String[] getServletMappings()
  31.  
  32. {
  33.  
  34. return new String[] { "/" };
  35.  
  36. }
  37.  
  38.  
  39. @Override
  40.  
  41. protected Filter[] getServletFilters() {
  42.  
  43. return new Filter[]{ new OpenEntityManagerInViewFilter() };
  44.  
  45. }
  46.  
  47. }

  

SpringWebAppInitializer.java中我们已经完成了以下的事情:

  • 配置了AppConfig.class 作为 RootConfirationClasses ,它将成为包含所有子上下文(DispatcherServlet)共享的bean定义的父ApplicationContext
  • 配置WebMvcConfig.class作为ServletConfigClasses,它是包括WebMvc bean定义的子ApplicationContext
  • 配置ServletMapping为”/”,让DispatcherServlet处理所有请求。
  • 注册OpenEntityManagerInViewFilter过滤器,用于展开视图时懒加载JPA实体集合。

第五步:创建JPA实体和Spring Data JPA repository
创建JPA实体User.java和User实体对应的Spring Data JPA repository。

  1. @Entity
  2.  
  3. public class User
  4.  
  5. {
  6.  
  7. @Id @GeneratedValue(strategy=GenerationType.AUTO)
  8.  
  9. private Integer id;
  10.  
  11. private String name;
  12.  
  13.  
  14. //setters and getters
  15.  
  16. }
  17.  
  18. public interface UserRepository extends JpaRepository<User, Integer>
  19.  
  20. {
  21.  
  22. }

  第六步:创建Spring MVC控制器
创建SpringMVC控制器来处理”/”URL请求并返回用户列表。

  1. @Controller
  2.  
  3. public class HomeController
  4.  
  5. {
  6.  
  7. @Autowired UserRepository userRepo;
  8.  
  9.  
  10. @RequestMapping("/")
  11.  
  12. public String home(Model model)
  13.  
  14. {
  15.  
  16. model.addAttribute("users", userRepo.findAll());
  17.  
  18. return "index";
  19.  
  20. }
  21.  
  22. }

  第七步:创建Thymeleaf视图:/WEB-INF/views/index.html来展示用户列表

  1. <!DOCTYPE html>
  2.  
  3. <html xmlns="http://www.w3.org/1999/xhtml"
  4.  
  5. xmlns:th="http://www.thymeleaf.org">
  6.  
  7. <head>
  8.  
  9. <meta charset="utf-8"/>
  10.  
  11. <title>Home</title>
  12.  
  13. </head>
  14.  
  15. <body>
  16.  
  17. <table>
  18.  
  19. <thead>
  20.  
  21. <tr>
  22.  
  23. <th>Id</th>
  24.  
  25. <th>Name</th>
  26.  
  27. </tr>
  28.  
  29. </thead>
  30.  
  31. <tbody>
  32.  
  33. <tr th:each="user : ${users}">
  34.  
  35. <td th:text="${user.id}">Id</td>
  36.  
  37. <td th:text="${user.name}">Name</td>
  38.  
  39. </tr>
  40.  
  41. </tbody>
  42.  
  43. </table>
  44.  
  45. </body>
  46.  
  47. </html>

  

我们准备好运行程序啦。但在此之前,我们需要下载和配置诸如Tomcat或者Jetty或者Wilddfly等容器。

你可以下载Tomcat 8并在你喜欢使用的IDE中配置并运行。然后打开浏览器访问http://localhost:8080/springmvcjpa-demo。你可以看到user的详细列表。
耶…我们做到了。

但是等一下~这不是花了非常多的工作量才能做一个从数据库中读取并显示用户列表信息吗?

我们公正公平来看问题。所有的这种配置并不只是一个用户案例。这个配置也是应用程序其它部分的基础。

回过头来,如果你只是想快速获得和运行一个应用来说这是在是太麻烦太复杂了。

另一个问题是,如果你想开发另一个有类似技术栈的 SpringMVC 应用吗?

好的,你可能为了拷贝粘贴这些配置而感到苦恼。是吗?提出一个记忆深刻的问题:如果你要做类似的事情重复一遍又一遍,那么你是不是想寻找一个能自动处理的方式解决问题。

各种分散的配置写了一遍又一遍,你会想到这里会有一些其他的麻烦问题吗?

好的,在这让我把这些我能想到的问题列出。

  • 你需要注意所有的类库的兼容性与 Spring 版本搭配和配置。
  • 在配置里面有 95% 的时间我们都是在配置 DataSourceEntityManagerFactoryTransactionManger 之类的实体。但如果 Spring 能够自动的为我们完成这些配置岂不是更好啊。
  • 类似的配置 SpringMVC 实体类比如 ViewResolverMessageSource 等又需要花更多的工作时间了。

想一想,要怎样才能让 Spring 能够自动化的完成配置实体?怎么样你才可以快速简单的使用基于可定制的属性完成自动的配置呢?

比如,将 DispacherServlet 的 url-pattern 映射 “/” 映射到 “/app/”。将 “/WEB-INF/views” 目录 替换为在 “/WEB-INF/templates/” 目录加入 Thymeleaf 视图。

所以基本上,你希望 Spring 自动执行一些操作,但是又能够提供更简单的方式灵活的提供重写默认配置?

好的,现在你正在走进 Spring Boot 的世界在里面你所期待已久的那些东西都已经有了!!!

快速上手品味 Spring Boot

欢迎来到 Spring Boot 世界!Spring Boot 并不是需要你完全地关注和掌握很多东西。它可以默认的完成自动化的配置但是你又可以按自己的需要去重新配置任意配置。

相比我更喜欢用一个例子来说明而不是更多的解析。

所以让我们现在开始用 Spring Boot 来快速构建一个应用。

Step 1:创建一个 Spring Boot 的 Maven 项目

创建一个 Maven 项目和(在 pom.xml 里面)配置项目 jar 包依赖如下:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2.  
  3. <project xmlns="http://maven.apache.org/POM/4.0.0"
  4.  
  5. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  6.  
  7. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
  8.  
  9. http://maven.apache.org/maven-v4_0_0.xsd">
  10.  
  11. <modelVersion>4.0.0</modelVersion>
  12.  
  13. <groupId>com.sivalabs</groupId>
  14.  
  15. <artifactId>hello-springboot</artifactId>
  16.  
  17. <packaging>jar</packaging>
  18.  
  19. <version>1.0-SNAPSHOT</version>
  20.  
  21. <name>hello-springboot</name>
  22.  
  23.  
  24. <parent>
  25.  
  26. <groupId>org.springframework.boot</groupId>
  27.  
  28. <artifactId>spring-boot-starter-parent</artifactId>
  29.  
  30. <version>1.3.2.RELEASE</version>
  31.  
  32. </parent>
  33.  
  34.  
  35. <properties>
  36.  
  37. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  38.  
  39. <java.version>1.8</java.version>
  40.  
  41. </properties>
  42.  
  43.  
  44.  
  45. <dependencies>
  46.  
  47. <dependency>
  48.  
  49. <groupId>org.springframework.boot</groupId>
  50.  
  51. <artifactId>spring-boot-starter-test</artifactId>
  52.  
  53. </dependency>
  54.  
  55. <dependency>
  56.  
  57. <groupId>org.springframework.boot</groupId>
  58.  
  59. <artifactId>spring-boot-starter-data-jpa</artifactId>
  60.  
  61. </dependency>
  62.  
  63. <dependency>
  64.  
  65. <groupId>org.springframework.boot</groupId>
  66.  
  67. <artifactId>spring-boot-starter-web</artifactId>
  68.  
  69. </dependency>
  70.  
  71. <dependency>
  72.  
  73. <groupId>org.springframework.boot</groupId>
  74.  
  75. <artifactId>spring-boot-starter-thymeleaf</artifactId>
  76.  
  77. </dependency>
  78.  
  79. <dependency>
  80.  
  81. <groupId>org.springframework.boot</groupId>
  82.  
  83. <artifactId>spring-boot-devtools</artifactId>
  84.  
  85. </dependency>
  86.  
  87. <dependency>
  88.  
  89. <groupId>mysql</groupId>
  90.  
  91. <artifactId>mysql-connector-java</artifactId>
  92.  
  93. </dependency>
  94.  
  95. </dependencies>
  96.  
  97. </project>

  

哇原来 pom.xml 的配置这么少感觉简单多了!

Step 2:在 application.properties 中配置数据源或JPA 属性配置如下:

  1. spring.datasource.driver-class-name=com.mysql.jdbc.Driver
  2.  
  3. spring.datasource.url=jdbc:mysql://localhost:3306/test
  4.  
  5. spring.datasource.username=root
  6.  
  7. spring.datasource.password=admin
  8.  
  9. spring.datasource.initialize=true
  10.  
  11. spring.jpa.hibernate.ddl-auto=update
  12.  
  13. spring.jpa.show-sql=true

  

你可以拷贝一些类似 data.sql 的文件到 src/main/resources 目录中。

Step 3:创建一些 JAP 实体类和实体类所需要的 Spring Data JAP Repository 接口

在 springmvc-jpa-demo 应用项目中创建 User.javaUserRepository.java 和 HomeController.java 之类所需的东西。

Step 4:用 Thymeleaf 模板语言创建一个显示用户列表的视图

在 springmvc-jap-demo 应用拷贝 /WEB-INF/views/index.html 到我们的新项目的 src/main/resources/templates 目录中。

Step 5:创建一个 SpringBoot 启动入口实体的类

创建一个有 main 函数的 Java 类 Application.java 如下:

  1. @SpringBootApplication
  2.  
  3. public class Application
  4.  
  5. {
  6.  
  7. public static void main(String[] args)
  8.  
  9. {
  10.  
  11. SpringApplication.run(Application.class, args);
  12.  
  13. }
  14.  
  15. }

  

现在用 Java Application 的方式开始启动运行 Application.java 之后打开浏览器访问 http://localhost:8080/

你就可以在页面的表格上看到用户列表的显示。这感觉实在太酷了!!!

OK 好的,我想你会大声说”这里边到底发生了做了些什么???”。

让我说明下刚才发生了什么

1. 轻松地依赖管理

  • 首要察觉一点是我们用的是一些名为spring-boot-starter-*.的依赖项。要记得我说过 “95%的时间里用的配置相同”。因此当默认添加springboot-starter-web依赖项时,它将在开发Spring-webmvcjackson-jsonvalidation-apitomcatSpring MVC应用程序中提取所有常用库。
  • 我们添加了spring-boot-starter-data-jpa依赖项。这会拉取所有spring-data-jpa依赖项并添加Hibernate库,因为大多数应用程序都把Hibernate作为JPA实施。

2. 自动配置

  • spring-boot-starter-web不仅添加了所有这些库,还配置了常见的bean,例如DispatcherServletResourceHandlersMessageSourcebean,具有合理的缺省值。
  • 我们还添加了spring-boot-starter-Thymeleaf,它不仅添加了Thymeleaf库依赖项,还自动配置了ThymeleafViewResolver bean
  • 我们并没有定义任何的DataSourceEntityManagerFactoryTransactionManageretc bean,但是它们会自动地创建。如何?如果我们的类路径中有任何像H2或是HSQL的内存数据库驱动程序,那么SpringBoot将自动创建一个内存中的DataSource,然后自动注册EntityManagerFactory,以及拥有合理的缺省值TransactionManager bean。但我们在用MySQL,所以我们需要提供明确的MySQL连接细节。我们在application.propertiesfile中配置了这些MySQL连接细节,并且SpringBoot使用了这些属性来创建一个DataSource

3.嵌入式Servlet容器支持

最重要也是最惊奇的是我们创建了一个简单的Java类,注释了一些神奇的注解@SpringApplication,它有一个main方法,通过运行main,我们可以运行应用程序并在http:// localhost:8080 /上访问它。

servlet容器从何而来?

我们已经添加了spring-boot-starter-web,它自动拉出spring-boot-starter-tomcat,当我们运行main()方法时,它为嵌入式容器启动了tomcat,这样我们就不必在任何外部安装的tomcat服务器上部署我们的应用程序了。

另外而言,你注意到我们在pom.xml中的打包类型是’jar’而不是’war’。 极其有趣!

好吧,但如果我想使用Jetty服务器而不用tomcat呢?

很简单,从spring-boot-starter-web中将spring-bootstarter-tomcat排除,只留有spring-boot-starter-jetty。

就是这样。

但是,这看起来很神奇!我可以想象你在想什么。你觉得SpringBoot看起来很酷,它会自动为我做很多事情。但我仍然没有完全理解它是如何真正在幕后工作的。对么?

我明白。观看魔术表演通常很有趣,但在软件开发中却没有。别担心,未来文章中我们将会查看这些内容,并详细解释幕后发生的事情。但是现在我不想在此文中将所有内容都转发给你,从而压倒你。

概要

在本文中,我们快速概述了各种Spring配置样式,并了解了配置Spring应用程序的复杂性。此外,我们通过创建一个简单的Web应用程序快速浏览了SpringBoot。

在下一篇文章中,我们将深入探讨SpringBoot并了解它是如何工作的。

 

来源代码湾:http://codebay.cn/post/10067.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号