环境 JavaSDKv1.6或更高版本。
这里使用maven作为构建工具
下面是一个典型的pom.xml文件:
配置pom.xml文件
<?xml version="1.0" encoding="utf-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="ht tp://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> <!-- Inherit defaults from Spring Boot --> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.4.0.BUILD-SNAPSHOT</version> </parent> <!-- Add typical dependencies for a web application --> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies> <!-- Package as an executable jar --> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> <!-- Add Spring repositories --> <!-- (you don't need this if you are using a .RELEASE versio n) --> <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>
spring-boot-starter-parent是使用Spring Boot的一种不错的方式,但它 并不总是最合适的。有时你可能需要继承一个不同的父POM,或只是不喜欢我们 的默认配置,那你可以使用import作用域这种替代方案:
编写代码
为了完成应用程序,我们需要创建一个单独的Java文件。Maven默认会编 译 src/main/java 下的源码,所以你需要创建那样的文件结构,并添加一个名 为 src/main/java/Example.java 的文件:import org.springframework.boot.*; @RequestMapping("/hello") public String hello(){ return "hello springBoot!"; } public static void main(String[] args) { SpringApplication.run(HelloSpringBoot.class,args); } }
运行示例
到此,示例应用可以工作了。由于使用了 spring-boot-starter-parent POM,这样我们就有了一个非常有用的run目标来启动程序。在项目根目录下输 入 mvn spring-boot:run 启动应用:
$ mvn spring-boot:run
. ____ _
如果使用浏览器打开localhost:8080,你应该可以看到如下输出:
Hello World!