本文不讲理论,直接写代码,运行出第一个springboot程序。
一、创建一个springboot的项目,要求maven支持。
在src/main/java下建立一个包com.example.myproject,在包下面建立一个类Application.class。
二、配置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>
<groupId>springboot</groupId>
<artifactId>springboot</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name />
<description />
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.0.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>springloaded</artifactId>
<version>1.2.5.RELEASE</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
</project>
三、编写Application类的内容。
package com.example.myproject;
import java.util.Date;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@EnableAutoConfiguration
public class Application {
@RequestMapping("/")
String home() {
return "Hello World!";
}
@RequestMapping("/now")
String hehe() {
return "现在时间:" + (new Date()).toLocaleString();
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
四、启动服务。注意,jdk要配成1.7,否则启动时报错。
检查项目引用的jdk版本,可以点击项目的properties查看。
运行项目
在Application类里运行main方法。
控制台显示如下信息,并且不报错即可。
五、运行程序
项目启动成功后,在浏览器中输入http://localhost:8080,则可显示Hello World!,说明配置成功。
也可以运行第二个当前时间的程序。
至此,spring boot的第一个程序编写完成。springboot的运行机制及原理等后续在介绍。