spring boot开箱即用设计,是Javaee开发的一场革命,大大简化了Javaee开发的繁琐配置,下面我们就来看一下一个例子吧,计算机编程的老规矩“hello world”
注意jdk最好使用1.7以上版本
点击 https://start.spring.io/ 创建一个spingboot项目,创建完毕下载
Group为包名 Artifact为工程名
将刚刚创建的工程导入ecplise,注意是maven工程!
POM.xml 添加maven的配置
<?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.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.7.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<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>
</plugin>
</plugins>
</build>
</project>
根据pom文件加载jar包,耐心等待片刻,我用的是阿里云的maven仓库镜像,没用过maven的同学自己百度!
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@EnableAutoConfiguration
@SpringBootApplication
public class Example {
@RequestMapping("/hello")
public String HelloWorld() {
return "Hello World";
}
public static void main(String[] args) {
SpringApplication.run(Example.class, args);
}
}
@RestController和@RequestMapping 注解解释:
@RequestMapping注解提供“路由”信息。 告诉Spring,任何具有路径“/hello”的HTTP请求都应映射到HelloWorld方法。
@RestController注解告诉Spring将生成的字符串直接返回给调用者。
@RestController和@RequestMapping注解是Spring MVC 的注解,它们并不是Spring Boot特有的。
@EnableAutoConfiguration注解解释:
@EnableAutoConfiguration。 这个注解告诉 Spring Boot 根据添加的jar依赖关系来配置Spring。由于spring-boot-starter-web添加了Tomcat和Spring MVC,自动配置Web应用程序并相应地配置Spring。
打开 http://localhost:8080 你应该看到浏览器输出:
Hello World