Spring Boot study notes 2 (create the first Spring Boot application)

1. The first Spring Boot application

Before starting, open a terminal to check if your java and maven versions are legal

$ java -version
java version "1.7.0_51"
Java(TM) SE Runtime Environment (build 1.7.0_51-b13)
Java HotSpot(TM) 64-Bit Server VM (build 24.51-b03, mixed mode)
$ mvn -v
Apache Maven 3.2.3 (33f8c3e1027c3ddde99d3cdebad2656a31e8fdf4; 2014-08-11T13:58:10-07:00)
Maven home: /Users/user/tools/apache-maven-3.1.1
Java version: 1.7.0_51, vendor: Oracle Corporation

1.1 Create pom.xml file

<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.example</groupId>
  <artifactId>myproject</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  
  <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.4.RELEASE</version>
    </parent>

    <!-- Add typical dependencies for a web application... -->
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

    <!-- (you don't need this if you are using a .RELEASE version) -->
    <!-- <repositories>
        <repository>
            <id>spring-snapshots</id>
            <url>http://repo.spring.io/snapshot</url>
            <snapshots><enabled>true</enabled></snapshots>
        </repository>
        <repository>
            <id>spring-milestones</id>
            <url>http://repo.spring.io/milestone</url>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>spring-snapshots</id>
            <url>http://repo.spring.io/snapshot</url>
        </pluginRepository>
        <pluginRepository>
            <id>spring-milestones</id>
            <url>http://repo.spring.io/milestone</url>
        </pluginRepository>
    </pluginRepositories> -->
</project>

1.2 Add classpath dependencies

Spring Boot provides a series of "Starters" that make it easy for you to import a jar into your classPath. Our sample program has used spring-boot-starter-parent in the parent node of the pom file. spring-boot-starter-parent is a special Starter that provides us with useful Maven default dependencies. It also has a dependency-management section so that you can ignore version numbers when referencing dependencies.

1.3 Writing code

Create a maven project and create a java class in the src/main/java directory

import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.*;
import org.springframework.stereotype.*;
import org.springframework.web.bind.annotation.*;

@RestController
@EnableAutoConfiguration
public class Example {

    @RequestMapping("/")
    String home() {
        return "Hello World!";
    }

    public static void main(String[] args) throws Exception {
        SpringApplication.run(Example.class, args);
    }

}

1.3.1 @RestController和@RequestMapping说明

我们的Example的第一个注解是@RestController。这是一个构造性注解。他暗示阅读代码的人和spring,该类扮演着一个特殊的角色。在本案例中,我们的class是一个web @controller。所以每当处理web请求时,Spring都会访问他。

@RequestMapping注解提供路由信息。他告诉Spring所有带有"/"路径的HTTP请求都应该被映射到这个方法。@RestController告诉Spring直接返回字符串结果集给调用者。

1.3.2 @EnableAutoConfiguration说明

这个注解告诉Spring Boot基于你添加的jar包去猜测你想怎样配置Spring。由于spring-boot-starter-web添加了Tomcat和Spring MVC,auto-configuration就会猜想你正在部署web项目并相应地设置Spring。

Starters and Auto-Configuration

Auto-configuration设计的初衷的为了更好地运行"Starters",但是两者没有直接的联系。你可以自行加入一些不在Starters的依赖,而Spring Boot会通过auto-configure自动配置到你的项目中。

1.3.3 Main方法

main方法只是一个遵循java习俗,为程序提供入口的标准方法。我们通过调用run方法,把main方法委托给Spring Boot的SpringApplication类。SpringApplication会引导我们的程序,依次地启动自动配置的Tomcat web服务器来启动Spring。我们需要把Example.class作为一个参数传入到run方法中,来告诉SpringApplication哪个才是主要的Spring主键。为了显示一切从命令行输入的参数,args数组也必须传入。

1.4 运行Example

因为我们已经在pom.xml中引入了spring-boot-starter-parent,所以有了可用的run目标,我们可以直接在项目的根目录下使用mvn spring-boot:run运行程序。如果你使用的是eclipse,右击项目,在run as的maven build的Goals中执行spring-boot:run。

$ mvn spring-boot:run

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::  (v1.3.4.RELEASE)
....... . . .
....... . . . (log output here)
....... . . .
........ Started Example in 2.222 seconds (JVM running for 6.514)

然后打开浏览器,访问 http://localhost:8080/,你可以看到以下输出:

Hello World!

1.5 生成可执行jar包

为了创建可执行的jar包,我们需要在pom.xml中加入spring-boot-maven-plugin。在dependencies部分的下面加入几行

   <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

保存pom.xml,然后在命令行窗口运行mvn package

$ mvn package

[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building myproject 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] .... ..
[INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ myproject ---
[INFO] Building jar: E:\Workspaces\spring_test\myproject\target\myproject-0.0.1-SNAPSHOT.jar
[INFO]
[INFO] --- spring-boot-maven-plugin:1.3.4.RELEASE:repackage (default) @ myproject ---
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------

运行成功后,在target目录下,可以看到myproject-0.0.1-SNAPSHOT.jar。大概是10M左右大小。如果你想偷看里面的内容,可以使用jar tvf:

使用java -jar命令来运行jar包程序

$ java -jar target/myproject-0.0.1-SNAPSHOT.jar

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::  (v1.3.4.RELEASE)
....... . . .
....... . . . (log output here)
....... . . .
........ Started Example in 2.536 seconds (JVM running for 2.864)

start.sh

#!/bin/sh
source ./app.cfg
rm -f tpid
#nohup java -jar $APP_NAME.jar --spring.profiles.active=bank_gray > /dev/null 2>&1 &
nohup /usr/local/jdk/bin/java -Xms512m -Xmx1024m -jar $APP_NAME.jar --spring.profiles.active=bank_gray > /dev/null 2>&1 &
echo $! > tpid
echo Start Success!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326004047&siteId=291194637