Skip to content

最近接触了一个SpringBoot项目,觉得十分简洁优雅,适合快速敏捷开发,和一些微服务的开发。😃

设计目的:

  • 特定的方式来进行配置,简化新Spring应用的初始搭建以及开发过程。

特点:

  • 创建独立的Spring应用程序
  • 嵌入的Tomcat,无需部署WAR文件
  • 简化Maven配置
  • 自动配置Spring
  • 提供生产就绪型功能,如指标,健康检查和外部配置
  • 绝对没有代码生成和对XML没有要求配置

那么如何规范的创建一个SpringBoot的项目呢?

  1. 一个pom.xml的配置模版
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/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.chiang.app</groupId>
    <artifactId>app</artifactId>
    <version>1.1.14-SNAPSHOT</version>
    <--  打包方式:jar或者war  -->
    <packaging>jar</packaging>

    <name>isn-server</name>
    <description>app-server project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.4.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>

    <organization>
        <name>Chiang. All rights reserved.</name>
        <url>https://ourvibes.github.com/</url>
    </organization>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <maven.build.timestamp.format>yyyy/MM/dd HH+8:mm:ss</maven.build.timestamp.format>
        <build-timestamp>${maven.build.timestamp}</build-timestamp>
        <spring-cloud.version>Dalston.SR1</spring-cloud.version>
        <svn-base>https://127.0.0.1:8888/svn/app/</svn-base>
        <jenkins-base>http://127.0.0.1:8080</jenkins-base>
        <mvn-repo>http://127.0.0.01:8081/nexus/content/repositories</mvn-repo>
        <maven.javadoc.failOnError>false</maven.javadoc.failOnError>
    </properties>

    <ciManagement>
        <system>Jenkins</system>
        <url>${jenkins-base}/job/app-server1.1-daily</url>
    </ciManagement>

    <scm>
        <connection>scm:svn:${svn-base}/Trunk/Development/Source/server/app-server1.1</connection>
        <developerConnection>scm:svn:${svn-base}/Trunk/Development/Source/server/app-server1.1</developerConnection>
        <url>${svn-base}/Trunk/Development/Source/server/app-server1.1</url>
    </scm>

    <repositories>
        <repository>
            <id>snapshots-repository</id>
            <name>snapshots-repository</name>
            <url>${mvn-repo}/snapshots</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
            <releases>
                <enabled>false</enabled>
            </releases>
        </repository>
        <repository>
            <id>releases-repository</id>
            <name>releases-repository</name>
            <url>${mvn-repo}/releases</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
            <releases>
                <enabled>true</enabled>
            </releases>
        </repository>
    </repositories>

    <distributionManagement>
        <repository>
            <id>nexus-releases</id>
            <url>${mvn-repo}/releases/</url>
        </repository>
        <snapshotRepository>
            <id>nexus-snapshots</id>
            <url>${mvn-repo}/snapshots</url>
            <uniqueVersion>true</uniqueVersion>
        </snapshotRepository>
    </distributionManagement>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-actuator-docs</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        
        <!-- 热部署,可以让项目自动加载变化的文件 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>org.jolokia</groupId>
            <artifactId>jolokia-core</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-feign</artifactId>
        </dependency>

        <!-- Swagger2 -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.7.0</version>
        </dependency>

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.7.0</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>

        <!-- spring cloud feign 上传文件 -->
        <dependency>
            <groupId>io.github.openfeign.form</groupId>
            <artifactId>feign-form</artifactId>
            <version>2.1.0</version>
        </dependency>

        <dependency>
            <groupId>io.github.openfeign.form</groupId>
            <artifactId>feign-form-spring</artifactId>
            <version>2.1.0</version>
        </dependency>

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.17</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.17</version>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-collections4</artifactId>
            <version>4.1</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.0</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.2.3</version>
        </dependency>
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper-spring-boot-starter</artifactId>
            <version>1.1.4</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>


        <!-- 单点登录相关开始 -->
        <dependency>
            <groupId>org.jasig.cas.client</groupId>
            <artifactId>cas-client-core</artifactId>
            <version>3.2.1</version>
            <exclusions>
                <exclusion>
                    <groupId>javax.servlet</groupId>
                    <artifactId>servlet-api</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <!-- 单点登录相关结束 -->
    </dependencies>
    
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
                <!-- 静态资源放行  -->
                <excludes>
                    <exclude>static/**</exclude>
                    <exclude>bin/ci.sh</exclude>
                </excludes>
                <includes>
                    <include>mybatis/**</include>
                    <include>bin/*.sh</include>
                    <include>*.yml</include>
                    <include>*.yaml</include>
                    <include>*.properties</include>
                    <include>*.xml</include>
                    <include>*.json</include>
                </includes>
            </resource>
            <!-- 静态资源 -->
            <resource>
                <directory>src/main/resources</directory>
                <filtering>false</filtering>
                <includes>
                    <include>static/**</include>
                </includes>
            </resource>
        </resources>


        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                            <goal>build-info</goal>
                        </goals>
                        <configuration>
                            <classifier>with-dependencies</classifier>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>*.properties</exclude>
                        <exclude>*.yaml</exclude>
                        <exclude>*.yml</exclude>
                        <exclude>*.json</exclude>
                    </excludes>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-release-plugin</artifactId>
                <configuration>
                    <tagBase>${svn-base}/Tags/CodeBase/server/app-server1.1</tagBase>
                    <allowTimestampedSnapshots>true</allowTimestampedSnapshots>
                    <autoVersionSubmodules>true</autoVersionSubmodules>
                    <preparationGoals>clean install</preparationGoals>
                    <useReleaseProfile>false</useReleaseProfile>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <configuration>
                    <skip>true</skip>
                    <testFailureIgnore>true</testFailureIgnore>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-assembly-plugin</artifactId>
                <configuration>
                    <descriptors>
                        <descriptor>src/assembly/distribution.xml</descriptor>
                    </descriptors>
                </configuration>
                <executions>
                    <execution>
                        <id>make-assembly</id>
                        <phase>package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-source-plugin</artifactId>
                <executions>
                    <execution>
                        <id>attach-sources</id>
                        <phase>package</phase>
                        <goals>
                            <goal>jar</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>animal-sniffer-maven-plugin</artifactId>
                <version>1.14</version>
                <configuration>
                    <signature>
                        <groupId>org.codehaus.mojo.signature</groupId>
                        <artifactId>java18</artifactId>
                        <version>1.0</version>
                    </signature>
                   <!--  <includeDependencies>true</includeDependencies> -->
                </configuration>
                <executions>
                    <execution>
                        <id>enforce-java-8</id>
                        <phase>test</phase>
                        <goals>
                            <goal>check</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            
        </plugins>
    </build>

</project>
  1. 目录和配置文件
  • 创建 src/main/resources 源文件目录,并在该目录下创建application.properties,static等文件夹。

  • 为了以后的开发方便,我们可以使用多环境配置。因此我们可以在src/main/resources 目录下新建三个配置文件,如需切换环境直接修改application.properties中的相关配置项即可。

  • application-dev.properties(用于开发环境)/ application-test.properties(用于测试环境)/ application-prod.properties(用于生产环境)

  1. 一个较为标准的application.properties配置文件,该文件主要是公共配置。
# Put this file on local or remote springcloud-config-server
# Set my name, keep me same as project name.
spring.application.name: @project.artifactId@

# This Application infomations
info.name: @project.artifactId@
info.description: @project.description@
info.version: @project.version@
info.buildtime: @build-timestamp@

# 环境配置
spring.profiles.active: dev

# Server setting
server.port: 2018
server.session.timeout: 3000
server.tomcat.uri-encoding: UTF-8

management.security.enabled: false

# LOGGING
logging.level.root: INFO

# Jackson
spring.jackson.time-zone: GMT+8

#pagehelper
pagehelper.helperDialect: mysql
pagehelper.reasonable: true
pagehelper.supportMethodsArguments: true
pagehelper.params: count=countSql
pagehelper.autoDialect: true  

#mybatis
mybatis.typeAliasesPackage: com.chiang.app.server.domain
mybatis.config-location: classpath:mybatis/mybatis-config.xml
mybatis.mapper-locations: classpath:mybatis/mapper/*Mapper.xml
spring.aop.auto: true
 
spring.http.encoding.charset: UTF-8
spring.http.encoding.enabled: true
spring.http.encoding.force: true

spring.http.multipart.enabled: true
spring.http.multipart.max-file-size: 512MB
spring.http.multipart.max-request-size: 512MB
spring.http.multipart.resolve-lazily: true


# 定时任务
sync.cron:0 0 4 * * *

audio.duration.time.limit: 240000
#audio.duration.time.limit:1

java代码中的项目入口:

java
@SpringBootApplication
@EnableSwagger2
@MapperScan("com.chiang.app.server.dao")
@EnableAspectJAutoProxy
@ServletComponentScan
@EnableTransactionManagement
@EnableFeignClients
public class IsnServerApplication {
    public static void main( String[] args ) {
        SpringApplication.run(AppServerApplication.class, args);
    }
}

4.前后端分离 swagger-ui,是用来显示RestfulAPI的,适用于后端对接口的测试和前端对接口的查看。由于在pom.xml文件中添加了依赖。这里不做过多描述,重点讲一下java代码中的配置。下面是一个较为标准的配置。

java
@Configuration
@EnableSwagger2
public class Swagger2Config {
    @Bean
    public Docket createRestApi() {
      return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select().apis(RequestHandlerSelectors.any())
        .paths(Predicates.not(PathSelectors.regex("/error.*")))
        .paths(Predicates.not(PathSelectors.regex("/info.*")))
        .paths(Predicates.not(PathSelectors.regex("/autoconfig.*")))
        .paths(Predicates.not(PathSelectors.regex("/health.*")))
        .paths(Predicates.not(PathSelectors.regex("/metrics.*")))
        .paths(Predicates.not(PathSelectors.regex("/mappings.*")))
        .paths(Predicates.not(PathSelectors.regex("/trace.*")))
        .paths(Predicates.not(PathSelectors.regex("/configprops.*")))
        .paths(Predicates.not(PathSelectors.regex("/beans.*")))
        .paths(Predicates.not(PathSelectors.regex("/env.*")))
        .paths(Predicates.not(PathSelectors.regex("/dump.*")))
        .paths(Predicates.not(PathSelectors.regex("/auditevents.*")))
        .paths(Predicates.not(PathSelectors.regex("/docs.*")))
        .paths(Predicates.not(PathSelectors.regex("/archaius.*")))
        .paths(Predicates.not(PathSelectors.regex("/features.*")))
        .paths(Predicates.not(PathSelectors.regex("/pause.*")))
        .paths(Predicates.not(PathSelectors.regex("/refresh.*")))
        .paths(Predicates.not(PathSelectors.regex("/resume.*")))
        .paths(Predicates.not(PathSelectors.regex("/actuator.*")))
        .paths(Predicates.not(PathSelectors.regex("/jolokia.*")))
        .paths(Predicates.not(PathSelectors.regex("/loggers.*")))
        .paths(Predicates.not(PathSelectors.regex("/restart.*")))
        .paths(Predicates.not(PathSelectors.regex("/service-registry/instance-status.*")))
        .paths(Predicates.not(PathSelectors.regex("/logfile.*")))
        .paths(Predicates.not(PathSelectors.regex("/heapdump.*"))).build();
    }

    /**
     * Swagger2主界面描述信息
     */
    private ApiInfo apiInfo() {
      return new ApiInfoBuilder().title("REST接口定义和规范").description("REST接口定义和规范").termsOfServiceUrl("https://ourvibes.github.com")
        .contact(new Contact("qzjiang@aliyun.com", "", "")).version("1.0").license("Chiang.All Rights Reserved.").build();
    }
}

掌握了这些基础的配置,那么就和以前的Spring + SpringMVC项目开发没什么大的区别了。

Powered by VitePress.