SpringBoot 【 第一章 】配置詳解

weixin_33806914發表於2019-01-25
13274833-0ae9f68407894c8b.jpg
image

Spring Boot 描述

世界上最好的文件來源自官方的《Spring Boot Reference Guide》,是這樣介紹的:

Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications that you can “just run”...Most Spring Boot applications need very little Spring configuration.

Spring Boot(英文中是“引導”的意思),是用來簡化Spring應用的搭建到開發的過程。應用開箱即用,只要通過 “just run”(可能是 java -jar 或 tomcat 或 maven外掛run 或 shell指令碼),就可以啟動專案。二者,Spring Boot 只要很少的Spring配置檔案(例如那些xml,property)。

因為“習慣優先於配置”的原則,使得Spring Boot在快速開發應用和微服務架構實踐中得到廣泛應用。

計算器實戰詳解

pom.xml配置

<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
  <!-- Spring Boot 啟動父依賴 -->
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>1.5.4.RELEASE</version>
</parent>

<groupId>com.androidmov.springcloud</groupId>
<artifactId>SpringCloud</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>SpringCloud</name>
<description>SpringCloud project with spring boot</description>

<properties>
  <main.basedir>${basedir}/../..</main.basedir>
  <m2eclipse.wtp.contextRoot>/</m2eclipse.wtp.contextRoot>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  <java.version>1.8</java.version>
  <commons.lang.version>2.6</commons.lang.version>
  <commons.net.version>3.6</commons.net.version>
  <jdbc.version>6.0.6</jdbc.version>
  <commons.config.version>1.10</commons.config.version>
</properties>

<dependencies>
  <!-- Spring Boot web依賴 -->
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <exclusions>
      <exclusion>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-logging</artifactId>
      </exclusion>
    </exclusions>
  </dependency>
  <!-- Spring Boot Log4j依賴 -->
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-log4j</artifactId>
    <version>1.3.8.RELEASE</version>
  </dependency>
  <dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
  </dependency>
  <!-- Spring Boot tomcat依賴 -->
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-tomcat</artifactId>
     <!--<scope>provided</scope>-->
  </dependency>
  <dependency>
    <groupId>org.apache.tomcat.embed</groupId>
    <artifactId>tomcat-embed-jasper</artifactId>
     <!--<scope>provided</scope>-->
  </dependency>
  <!-- Spring Boot Spring-data-jpa 資料依賴 -->
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
  </dependency>
  <dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <!-- <scope>runtime</scope> -->
  </dependency>
  <!-- Spring Boot mysql依賴 -->
  <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <!--<scope>runtime</scope>-->
  </dependency>
  <!-- Spring Boot 本地版本庫 -->
  <dependency>
    <groupId>com.amt</groupId>
    <artifactId>tools</artifactId>
    <version>1.0.1</version>
  </dependency>

  <!-- mongoDB dependency -->
  <!--<dependency>-->
    <!--<groupId>org.springframework.boot</groupId>-->
    <!--<artifactId>spring-boot-starter-data-mongodb</artifactId>-->
  <!--</dependency>-->
  <!--<dependency>-->
    <!--<groupId>org.mongodb</groupId>-->
    <!--<artifactId>mongo-java-driver</artifactId>-->
    <!--<version>3.5.0</version>-->
  <!--</dependency>-->

  <!-- Spring Boot lang依賴 -->
  <dependency>
      <groupId>commons-lang</groupId>
      <artifactId>commons-lang</artifactId>
      <version>${commons.lang.version}</version>
  </dependency>
  <dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.6</version>
  </dependency>
  <dependency>
    <groupId>commons-configuration</groupId>
    <artifactId>commons-configuration</artifactId>
    <version>${commons.config.version}</version>
  </dependency>
  <dependency>
    <groupId>commons-net</groupId>
    <artifactId>commons-net</artifactId>
    <version>${commons.net.version}</version>
  </dependency>
  <dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.4</version>
  </dependency>

  <dependency>
    <groupId>org.apache.ant</groupId>
    <artifactId>ant</artifactId>
    <version>1.10.1</version>
  </dependency>

  <!-- Spring Boot test依賴 -->
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
  </dependency>
  <dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-eureka-server</artifactId>
  </dependency>
  <!-- Spring Boot web依賴 -->
  <dependency>
    <groupId>org.springframework.kafka</groupId>
    <artifactId>spring-kafka</artifactId>
    <version>1.1.1.RELEASE</version>
  </dependency>
  <!-- Spring Boot amqp依賴 -->
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-amqp</artifactId>
  </dependency>
</dependencies>
<!-- Spring cloud 版本依賴 -->
<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-dependencies</artifactId>
      <version>Dalston.SR1</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>
<build>
  <finalName>springCloud</finalName>
  <plugins>
    <!-- maven依賴 -->
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-war-plugin</artifactId>
      <configuration>
        <warName>springCloud</warName>
      </configuration>
    </plugin>
    <plugin>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-maven-plugin</artifactId>
    </plugin>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-surefire-plugin</artifactId>
      <configuration>
        <useSystemClassLoader>false</useSystemClassLoader>
      </configuration>
    </plugin>
  </plugins>
</build>
</project>

啟動應用類

package com.androidmov.adManagement;

import com.androidmov.adManagement.common.utils.configs.UtilConfig;
import org.apache.commons.configuration.Configuration;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;

/**
 * Created by cw on 2017/10/25. good day.
 *
 * @Author: Chen Wu
 * Blog: http://www.updatecg.xin
 */

@EnableEurekaServer
@SpringBootApplication
@RestController
@EnableScheduling
@EnableConfigurationProperties
public class EureKaServer extends SpringBootServletInitializer implements CommandLineRunner {

  public static void main(String[] args) {
      createLocalTempDirectory();
      SpringApplication.run(EureKaServer.class, args);
  }



  /**
   * 使用SpringBoot初始化Servlet配置並能夠部署至tomcat使專案執行
   * @param builder
   * @return
   */
  @Override
  protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
      return builder.sources(EureKaServer.class);
  }

  /**
   * 依據配置檔案建立本地目錄
   */
  protected static void createLocalTempDirectory(){
      Configuration cfg = UtilConfig.getApp();
      File tmpFile = new File(cfg.getString("tmpFilePath"));
      tmpFile.mkdirs();
  }

  @Override
  public void run(String... strings) throws Exception {
      System.out.println("=========Application init============");
  }
}
  • @SpringBootApplication:Spring Boot 應用的標識 (必須)
  • @EnableEurekaServer:Spring Cloud 註冊註解
  • @RestController是@Controller和@ResponseBody的結合體,兩個標註合併起來的作用。
  • @EnableScheduling: 定時器
  • @EnableConfigurationProperties:配置檔案啟用
  • Application很簡單,一個main函式作為主入口。SpringApplication引導應用,並將Application本身作為引數傳遞給run方法。具體run方法會啟動嵌入式的Tomcat並初始化Spring環境及其各Spring元件。

Controller層類

package com.androidmov.adManagement.maker.controllers;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

  /**
  * Created by cw on 2017/10/25. good day.
  *
  * @Author: Chen Wu
  * Blog: http://www.updatecg.xin
  */
  @RestController
  public class ComputeController {

    private final Logger logger = Logger.getLogger(getClass());

    @Autowired
    private DiscoveryClient client;

    @RequestMapping(value = "/add" ,method = RequestMethod.POST)
    public Integer add(@RequestParam (value = "a",required = true) Integer a, @RequestParam(value = "b",required = true)  Integer b) {
        ServiceInstance instance = client.getLocalServiceInstance();
        Integer r = a + b;
        logger.info("/add, host:" + instance.getHost() + ", service_id:" + instance.getServiceId() + ", result:" + r);
        return r;
    }
  }

結果

Run執行ComputeController類,測試結果。
控制檯顯示

[FrameworkServlet 'dispatcherServlet': initialization completed in 41 ms]
[/add, host:AMT-20160520COB, service_id:rabbitmq-hello, result:30]

postman測試
[圖片上傳失敗...(image-fb8a42-1548395711751)]

<strong>對應程式碼分享在 [https://github.com/UpdateCw/SpringBoot]</strong>

相關文章