天天看點

Why Spring Boot

本文介紹将各種Spring的配置方式,幫助您了解配置Spring應用的複雜性。

Spring是一個非常受歡迎的Java架構,它用于建構web和企業應用。不像許多其他架構隻關注一個領域,Spring架構提供了各種功能,通過項目組合來滿足當代業務需求。

Spring架構提供了多種靈活的方式配置Bean。例如XML、注解和Java配置。随着功能數量的增加,複雜性也随之增加,配置Spring應用将變得乏味而且容易出錯。

Spring團隊建立了Spring Boot以解決配置複雜的問題。

但在開始Spring Boot之前,我們将快速浏覽一下Spring架構,看看Spring Boot正在決解什麼樣的問題。

在本文中,我們将介紹:

  • Spring架構概述
  • 一個使用了Spring MVC和JPA(Hibernate)的web應用
  • 快速嘗試Spring Boot

https://blog.didispace.com/why-spring-boot-tran/#Spring%E6%A1%86%E6%9E%B6%E6%A6%82%E8%BF%B0

如果您是一名Java開發人員,那麼您很可能聽說過Spring架構,甚至可能已經在您的項目中使用了它。Spring架構主要是作為依賴注入容器,但它不僅僅是這樣。

https://blog.didispace.com/why-spring-boot-tran/#Spring%E5%BE%88%E5%8F%97%E6%AC%A2%E8%BF%8E%E7%9A%84%E5%8E%9F%E5%9B%A0%E6%9C%89%E5%87%A0%E7%82%B9%EF%BC%9A Spring很受歡迎的原因有幾點:

  • Spring的依賴注入方式鼓勵編寫可測試代碼。
  • 具備簡單但功能強大的資料庫事務管理功能
  • Spring簡化了與其他Java架構的內建工作,比如JPA/Hibernate ORM和Struts/JSF等web架構。
  • 建構web應用最先進的Web MVC架構。

連同Spring一起的,還有許多其他的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、注解和基于Java配置的方式來配置bean。

讓我們快速了解一下這些配置風格的大概樣子。

https://blog.didispace.com/why-spring-boot-tran/#%E5%9F%BA%E4%BA%8EXML%E7%9A%84%E9%85%8D%E7%BD%AE 基于XML的配置

<bean id="userService" class="com.sivalabs.myapp.service.UserService">
    <property name="userDao" ref="userDao"/>
</bean>
<bean id="userDao" class="com.sivalabs.myapp.dao.JdbcUserDao">
    <property name="dataSource" ref="dataSource"/>
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    <property name="url" value="jdbc:mysql://localhost:3306/test"/>
    <property name="username" value="root"/>
    <property name="password" value="secret"/>
</bean>      

基于注解的配置

@Service
public class UserService
{
    private UserDao userDao;
    @Autowired
    public UserService(UserDao dao){
        this.userDao = dao;
    }
    ...
    ...
}      
@Repository
public class JdbcUserDao
{
    private DataSource dataSource;
    @Autowired
    public JdbcUserDao(DataSource dataSource){
        this.dataSource = dataSource;
    }
    ...
    ...
}      

基于Java配置

@Configuration
public class AppConfig
{
    @Bean
    public UserService userService(UserDao dao){
        return new UserService(dao);
    }
    @Bean
    public UserDao userDao(DataSource dataSource){
        return new JdbcUserDao(dataSource);
    }
    @Bean
    public DataSource dataSource(){
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/test");
        dataSource.setUsername("root");
        dataSource.setPassword("secret");
        return dataSource;
    }
}      

哇!Spring提供給了許多方法來做同樣的事,我們甚至可以混合使用,在同一個應用中使用基于Java配置和注解配置的方式。

這非常靈活,但它有好有壞。剛開始接觸Spring的新人可能會困惑應該使用哪一種方式。到目前為止,Spring團隊建議使用基于Java配置的方式,因為它具有更多的靈活性。

沒有哪一種方案是萬能,我們應該根據自己的需求來選擇合适的方式。

很好,現在您已經了解了多種Spring Bean的配置方式的基本形式。

讓我們快速地了解一下典型的Spring MVC+JPA/Hibernate web應用的配置。

https://blog.didispace.com/why-spring-boot-tran/#%E4%B8%80%E4%B8%AA%E4%BD%BF%E7%94%A8%E4%BA%86Spring-MVC%E5%92%8CJPA%EF%BC%88Hibernate%EF%BC%89%E7%9A%84web%E5%BA%94%E7%94%A8

在了解Spring Boot是什麼以及它提供了什麼樣的功能之前,我們先來看一下典型的Spring Web應用配置是怎樣的,哪些是痛點,然後我們将讨論Spring Boot是如何解決這些問題的。

https://blog.didispace.com/why-spring-boot-tran/#%E6%AD%A5%E9%AA%A41%EF%BC%9A%E9%85%8D%E7%BD%AEMaven%E4%BE%9D%E8%B5%96 步驟1:配置Maven依賴

首先我們需要做的是配置pom.xml中所需的依賴。

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
                        http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.sivalabs</groupId>
    <artifactId>springmvc-jpa-demo</artifactId>
    <packaging>war</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>springmvc-jpa-demo</name>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>      
        <failOnMissingWebXml>false</failOnMissingWebXml>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.2.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
            <version>1.9.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <version>1.7.13</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.13</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.13</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <version>1.4.190</version>
        </dependency>
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>1.4</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.38</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>4.3.11.Final</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf-spring4</artifactId>
            <version>2.1.4.RELEASE</version>
        </dependency>
    </dependencies>
</project>      

我們配置了所有的Maven jar依賴,包括Spring MVC、Spring Data JPA、JPA/Hibernate、Thymeleaf和Log4j。

https://blog.didispace.com/why-spring-boot-tran/#%E6%AD%A5%E9%AA%A42%EF%BC%9A%E4%BD%BF%E7%94%A8Java%E9%85%8D%E7%BD%AE%E9%85%8D%E7%BD%AEService-DAO%E5%B1%82%E7%9A%84Bean 步驟2:使用Java配置配置Service/DAO層的Bean

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages="com.sivalabs.demo")
@PropertySource(value = { "classpath:application.properties" })
public class AppConfig 
{
    @Autowired
    private Environment env;
    @Bean
    public static PropertySourcesPlaceholderConfigurer placeHolderConfigurer()
    {
        return new PropertySourcesPlaceholderConfigurer();
    }
    @Value("${init-db:false}")
    private String initDatabase;
    @Bean
    public PlatformTransactionManager transactionManager()
    {
        EntityManagerFactory factory = entityManagerFactory().getObject();
        return new JpaTransactionManager(factory);
    }
    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory()
    {
        LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        vendorAdapter.setGenerateDdl(Boolean.TRUE);
        vendorAdapter.setShowSql(Boolean.TRUE);
        factory.setDataSource(dataSource());
        factory.setJpaVendorAdapter(vendorAdapter);
        factory.setPackagesToScan("com.sivalabs.demo");
        Properties jpaProperties = new Properties();
        jpaProperties.put("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
        factory.setJpaProperties(jpaProperties);
        factory.afterPropertiesSet();
        factory.setLoadTimeWeaver(new InstrumentationLoadTimeWeaver());
        return factory;
    }
    @Bean
    public HibernateExceptionTranslator hibernateExceptionTranslator()
    {
        return new HibernateExceptionTranslator();
    }
    @Bean
    public DataSource dataSource()
    {
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
        dataSource.setUrl(env.getProperty("jdbc.url"));
        dataSource.setUsername(env.getProperty("jdbc.username"));
        dataSource.setPassword(env.getProperty("jdbc.password"));
        return dataSource;
    }
    @Bean
    public DataSourceInitializer dataSourceInitializer(DataSource dataSource) 
    {
        DataSourceInitializer dataSourceInitializer = new DataSourceInitializer();
        dataSourceInitializer.setDataSource(dataSource);
        ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator();
        databasePopulator.addScript(new ClassPathResource("data.sql"));
        dataSourceInitializer.setDatabasePopulator(databasePopulator);
        dataSourceInitializer.setEnabled(Boolean.parseBoolean(initDatabase));
        return dataSourceInitializer;
    }   
}      

在AppConfig.java配置類中,我們完成了以下操作:

  • 使用

    @Configuration

    注解标記為一個Spring配置類。
  • @EnableTransactionManagement

    開啟基于注解的事務管理。
  • 配置

    @EnableJpaRepositories

    指定去哪查找Spring Data JPA資源庫(repository)。
  • @PropertySource

    注解和

    PropertySourcesPlaceholderConfigurer

    Bean定義配置PropertyPlaceHolder bean從

    application.properties

    檔案加載配置。
  • 為DataSource、JAP的EntityManagerFactory和JpaTransactionManager定義Bean。
  • 配置DataSourceInitializer Bean,在應用啟動時,執行

    data.sql

    腳本來初始化資料庫。

我們需要在

application.properties

中完善配置,如下所示:

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.username=root
jdbc.password=admin
init-db=true
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=update      

我們可以建立一個簡單的SQL腳本

data.sql

來将示範資料填充到USER表中:

delete from user;
insert into user(id, name) values(1,'Siva');
insert into user(id, name) values(2,'Prasad');
insert into user(id, name) values(3,'Reddy');      

我們可以建立一個附帶基本配置的

log4j.properties

檔案,如下所示:

log4j.rootCategory=INFO, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p %t %c{2}:%L - %m%n
log4j.category.org.springframework=INFO
log4j.category.com.sivalabs=DEBUG      

步驟3:配置Spring MVC Web層的Bean

我們必須配置Thymleaf的ViewResolver、處理靜态資源的ResourceHandler和處理i18n的MessageSource等。

@Configuration
@ComponentScan(basePackages = { "com.sivalabs.demo"}) 
@EnableWebMvc
public class WebMvcConfig extends WebMvcConfigurerAdapter
{
    @Bean
    public TemplateResolver templateResolver() {
        TemplateResolver templateResolver = new ServletContextTemplateResolver();
        templateResolver.setPrefix("/WEB-INF/views/");
        templateResolver.setSuffix(".html");
        templateResolver.setTemplateMode("HTML5");
        templateResolver.setCacheable(false);
        return templateResolver;
    }
    @Bean
    public SpringTemplateEngine templateEngine() {
        SpringTemplateEngine templateEngine = new SpringTemplateEngine();
        templateEngine.setTemplateResolver(templateResolver());
        return templateEngine;
    }
    @Bean
    public ThymeleafViewResolver viewResolver() {
        ThymeleafViewResolver thymeleafViewResolver = new ThymeleafViewResolver();
        thymeleafViewResolver.setTemplateEngine(templateEngine());
        thymeleafViewResolver.setCharacterEncoding("UTF-8");
        return thymeleafViewResolver;
    }
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry)
    {
        registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
    }
    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer)
    {
        configurer.enable();
    }
    @Bean(name = "messageSource")
    public MessageSource configureMessageSource()
    {
        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        messageSource.setBasename("classpath:messages");
        messageSource.setCacheSeconds(5);
        messageSource.setDefaultEncoding("UTF-8");
        return messageSource;
    }
}      

在WebMvcConfig.java配置類中,我們完成了以下操作:

  • @Configuration

  • @EnableWebMvc

    注解啟用基于注解的Spring MVC配置。
  • 通過注冊TemplateResolver、SpringTemplateEngine和`hymeleafViewResolver Bean來配置Thymeleaf視圖解析器。
  • 注冊ResourceHandler Bean将以URI為

    /resource/**

    的靜态資源請求定位到

    /resource/

    目錄下。
  • 配置MessageSource bean從classpath下加載messages-{國家代碼}.properties檔案來加載i18n配置。

現在我們沒有配置任何i18n内容,是以需要在

src/main/resources

檔案夾下建立一個空的

messages.properties

檔案。

https://blog.didispace.com/why-spring-boot-tran/#%E6%AD%A5%E9%AA%A44%EF%BC%9A%E6%B3%A8%E5%86%8CSpring-MVC%E7%9A%84%E5%89%8D%E7%AB%AF%E6%8E%A7%E5%88%B6%E5%99%A8DispatcherServlet 步驟4:注冊Spring MVC的前端控制器DispatcherServlet

在Servlet 3.x規範之前,我們必須在web.xml中注冊Servlet/Filter。由于目前是Servlet 3.x規範,我們可以使用ServletContainerInitializer以程式設計的方式注冊Servlet

/Filter。

Spring MVC提供了一個慣例類AbstractAnnotationConfigDispatcherServletInitializer來注冊DispatcherServlet。

public class SpringWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer
{
    @Override
    protected Class<?>[] getRootConfigClasses()
    {
        return new Class<?>[] { AppConfig.class};
    }
    @Override
    protected Class<?>[] getServletConfigClasses()
    {
        return new Class<?>[] { WebMvcConfig.class };
    }
    @Override
    protected String[] getServletMappings()
    {
        return new String[] { "/" };
    }
    @Override
    protected Filter[] getServletFilters() {
       return new Filter[]{ new OpenEntityManagerInViewFilter() };
    }
}      

在SpringWebAppInitializer.java配置類中,我們完成了以下操作:

  • 我們将

    AppConfig.class

    配置為RootConfigurationClass,它将成為包含了所有子上下文(DispatcherServlet)共享的Bean定義的父ApplicationContext。
  • WebMvcConfig.class

    配置為ServletConfigClass,它是包含了WebMvc Bean定義的子ApplicationContext。
  • /

    配置為ServletMapping,這意味所有的請求将由DispatcherServlet處理。
  • 我們将OpenEntityManagerInViewFilter注冊為Servlet過濾器,以便我們在渲染視圖時可以延遲加載JPA Entity的延遲集合。

https://blog.didispace.com/why-spring-boot-tran/#%E6%AD%A5%E9%AA%A45%EF%BC%9A%E5%88%9B%E5%BB%BA%E4%B8%80%E4%B8%AAJPA%E5%AE%9E%E4%BD%93%E5%92%8CSpring-Data-JPA%E8%B5%84%E6%BA%90%E5%BA%93 步驟5:建立一個JPA實體和Spring Data JPA資源庫

為User實體建立一個JPA實體User.java和一個Spring Data JPA資源庫。

@Entity
public class User
{
    @Id @GeneratedValue(strategy=GenerationType.AUTO)
    private Integer id;
    private String name;
    //setters and getters
}      
public interface UserRepository extends JpaRepository<User, Integer>
{
}      

步驟6:建立一個Spring MVC控制器

建立一個Spring MVC控制器來處理URL為

/

,并渲染一個使用者清單。

@Controller
public class HomeController
{
    @Autowired UserRepository userRepo;
    @RequestMapping("/")
    public String home(Model model)
    {
        model.addAttribute("users", userRepo.findAll());
        return "index";
    }
}      

步驟7:建立一個Thymeleaf視圖/WEB-INF/views/index.html來渲染使用者清單

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8"/>
<title>Home</title>
</head>
<body>
    <table>
        <thead>
            <tr>
                <th>Id</th>
                <th>Name</th>
            </tr>
        </thead>
        <tbody>
            <tr th:each="user : ${users}">
                <td th:text="${user.id}">Id</td>
                <td th:text="${user.name}">Name</td>
            </tr>
        </tbody>
    </table>
</body>
</html>      

我們都配置好了,可以運作應用了。但在此之前,我們需要在您的IDE中下載下傳并配置像Tomcat、Jetty或者Wildfly等伺服器。

您可以下載下傳Tomcat 8并配置在您喜歡的IDE中,之後運作應用并将浏覽器指向

http://localhost:8080/springmvc-jpa-demo

。您應該看到一個以表格形式展示的使用者詳細資訊清單。

Yay…( •̀ ω •́ )y,我們做到了。

但是等等,做了那麼多的工作僅僅是為了從資料庫中擷取使用者資訊然後展示一個清單?

讓我們誠實公平地來看待,所有的這些配置不僅僅是為了這次示例,這些配置也是其他應用的基礎。

但我還是想說,如果您想早點起床跑步,這有太多的工作要做。

另一個問題是,假設您想要開發另一個Spring MVC應用,您會使用類似的技術棧?

好,您要做的就是複制粘貼配置并調整它。對麼?但請記住一件事:如果您一次又一次地做同樣的事情,您應該尋找一種自動化的方式來完成它。

除了一遍又一遍地編寫相同的配置,您還能發現其他問題麼?

這樣吧,讓我列出我從中發現的問題。

  • 您需要尋找特定版本的Spring以便完全相容所有的庫,并進行配置。
  • 我們花費了95%的時間以同樣的方式配置DataSource、EntityManagerFactory和TransactionManager等bean。如果Spring能自動幫我們完成這些事,是不是非常棒?
  • 同樣,我們大多時候以同樣的方式配置Spring MVC的bean,比如ViewResolver、MessageResource等。
如果Spring可以自動幫我做這些事情,那真的非常棒!!!

想象一下,如果Spring能夠自動配置bean呢?如果您可以使用簡單的自定義配置來定義自動配置又将怎麼樣?

例如,您可以将DispatcherServlet的url-pattern映射到

/app/

,而不是

/

。您可以将Theymeleaf視圖放在

/WEB-INF/template/

檔案夾下,而不是放在

/WEB-INF/views

中。

是以基本上您希望Spring能自動執行這些操作,但是它有沒有提供一個簡單靈活的方式來覆寫掉預設配置呢?

很好,您即将進入Spring Boot的世界,您将夢想成真!

https://blog.didispace.com/why-spring-boot-tran/#%E5%BF%AB%E9%80%9F%E5%B0%9D%E8%AF%95Sprig-Boot 快速嘗試Sprig Boot

歡迎來到Spring Boot世界!Spring Boot正是您一直在尋找的。它可以自動為您完成某些事情,但如果有必要,您可以覆寫掉預設配置。

與拿理論解釋相比,我更喜歡通過案例來講解。

https://blog.didispace.com/why-spring-boot-tran/#%E6%AD%A5%E9%AA%A41%EF%BC%9A%E5%88%9B%E5%BB%BA%E4%B8%80%E4%B8%AA%E5%9F%BA%E4%BA%8EMaven%E7%9A%84Spring-Boot%E5%BA%94%E7%94%A8 步驟1:建立一個基于Maven的Spring Boot應用

建立一個Maven項目并配置如下依賴:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
                        http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.sivalabs</groupId>
    <artifactId>hello-springboot</artifactId>
    <packaging>jar</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>hello-springboot</name>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.2.RELEASE</version>
    </parent>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
    </dependencies>
</project>      

哇!我們的pom.xml檔案一下子變小了許多!

https://blog.didispace.com/why-spring-boot-tran/#%E6%AD%A5%E9%AA%A42%EF%BC%9A%E5%A6%82%E4%B8%8B%E5%9C%A8application-properties%E4%B8%AD%E9%85%8D%E7%BD%AEDataSoure-JPA 步驟2:如下在application.properties中配置DataSoure/JPA

spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=admin
spring.datasource.initialize=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true      

您可以将相同的data.sql檔案拷貝到

src/main/resources

檔案加中。

https://blog.didispace.com/why-spring-boot-tran/#%E6%AD%A5%E9%AA%A43%EF%BC%9A%E4%B8%BA%E5%AE%9E%E4%BD%93%E5%88%9B%E5%BB%BA%E4%B8%80%E4%B8%AAJPA%E5%AE%9E%E4%BD%93%E5%92%8CSpring-Data-JPA%E8%B5%84%E6%BA%90%E5%BA%93%E6%8E%A5%E5%8F%A3 步驟3:為實體建立一個JPA實體和Spring Data JPA資源庫接口

springmvc-jpa-demo

應用一樣,建立User.java、UserRepository.java和HomeController.java。

https://blog.didispace.com/why-spring-boot-tran/#%E6%AD%A5%E9%AA%A44%EF%BC%9A%E5%88%9B%E5%BB%BA%E7%94%A8%E4%BA%8E%E6%98%BE%E7%A4%BA%E7%94%A8%E6%88%B7%E5%88%97%E8%A1%A8%E7%9A%84Thymeleaf%E8%A7%86%E5%9B%BE 步驟4:建立用于顯示使用者清單的Thymeleaf視圖

springmvc-jpa-demo

項目中複制之前建立的

/WEB-INF/views/index.html

src/main/resources/template

檔案夾中。

https://blog.didispace.com/why-spring-boot-tran/#%E6%AD%A5%E9%AA%A45%EF%BC%9A%E5%88%9B%E5%BB%BASpring-Boot%E5%85%A5%E5%8F%A3%E7%B1%BB 步驟5:建立Spring Boot入口類

建立一個含有

main

方法的Java類Application.java,如下所示:

@SpringBootApplication
public class Application
{
    public static void main(String[] args)
    {
        SpringApplication.run(Application.class, args);
    }
}      

現在把

Application.java

當作一個Java應用運作,并将您的浏覽其指向

http://localhost:8080/

您應該可以看到以表格的形式展示的使用者清單,真的很酷!

很好,我聽到您在喊:“到底發生了什麼事???”。

讓我解釋剛剛所發生的事情。

  1. 簡單的依賴管理
    • 首先要注意的是我們正在使用一些名為

      spring-boot-start-*

      的依賴。記住我說過我花費95%的時間來配置同樣的配置。當您在開發Spring MVC應用時添加了

      spring-boot-start-web

      依賴,它已經包含了常用的一些庫,比如spring-webmvc、jackson-json、validation-api和tomcat等。
    • 我們添加了

      spring-boot-starter-data-jpa

      依賴。它包含了所有的

      spring-data-jpa

      依賴,并且還添加了Hibernate庫,因為很多應用使用Hibernate作為JPA的實作。
  1. 自動配置
    • spring-boot-starter-web

      不僅添加了這些庫,還配置了經常被注冊的bean,比如DispatcherServlet、ResourceHandler和MessageSource等bean,并且應用了合适的預設配置。
    • 我們還添加了

      spring-boot-starter-Thymeleaf

      ,它不僅添加了Thymeleaf的依賴,還自動配置了ThymeleafViewResolver bean。
    • 雖然我們沒有定義任何DataSource、EntityManagerFactory和TransactionManager等bean,但它們可以被自動建立。怎麼樣?如果在classpath下沒有任何記憶體資料庫驅動,如H2或者HSQL,那麼Spring Boot将自動建立一個記憶體資料庫的DataSource,然後應用合理的預設配置自動注冊EntityManagerFactory和TransactionManager等bean。但是我們正在使用MySQL,是以我們需要明确提供MySQL的連接配接資訊。我們已經在

      application.properties

      檔案中配置了MySQL連接配接資訊,Spring Boot将應用這些配置來建立DataSource。
  1. 支援嵌入式Servlet容器
    • 最重要且最讓人驚訝的是,我們建立了一個簡單的Java類,标記了一個神奇的注解

      @SpringApplication

      ,它有一個main方法。通過運作main方法,我們可以運作這個應用并通過

      http://localhost:8080/

      來通路。

https://blog.didispace.com/why-spring-boot-tran/#Servlet%E5%AE%B9%E5%99%A8%E6%9D%A5%E8%87%AA%E5%93%AA%E9%87%8C%EF%BC%9F Servlet容器來自哪裡?

spring-boot-starter-web

,它會自動引入

spring-boot-starter-tomcat

。當我們運作main()方法時,它将tomcat作為一個嵌入式容器啟動,我們不需要部署我們的應用到外部安裝好的tomcat上。

順便說一句,您看到我們在pom.xml中配置的打包類型是jar而不是war,真有趣!

很好,但是如果我想使用jetty伺服器而不是tomcat呢?很簡單,隻需要從

spring-boot-starter-web

中排除掉

sprig-boot-starter-tomcat

,并包含

spring-boot-starter-jetty

依賴即可。

就是這樣。

但是,這看起來真的很神奇!!!

我可以想象此時您在想什麼。您正在感歎Spring Boot真的很酷,它為我自動完成了很多事情。但是,我還沒了完全明白它幕後是怎樣工作的,對不對?

我可以了解,觀看魔術表演是非常有趣的,但軟體開發則不一樣,不用擔心,未來我們将看到各種新奇的東西,并在以後的文章中詳細地解釋它們幕後的工作原理。很遺憾的是,我不能在這篇文章中把所有的東西都教給您。

https://blog.didispace.com/why-spring-boot-tran/#%E6%80%BB%E7%BB%93 總結

在本文中,我們快速介紹了各種Spring配置的樣式,并了解了配置Spring應用的複雜型。此外,我們通過建立一個簡單的web應用來快速了解Spring Boot。