HelloWorld详解
接下来我们通过maven脚手架工具快速生成一个项目,并通过手动配置写出第一个基于springBoot的web可运行项目.
- 首先,再命令提示行下输入:
mvn archetype:generate -DgroupId=springboot -DartifactId=helloworld -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
如下图所示:
2.添加SpringBoot启动父类依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-parent</artifactId>
<version>2.1.3.RELEASE</version>
</parent>
这样项目会继承父类的pom默认配置,我们进入父类的pom配置,可以看到父类的pom定义了很多jar包版本,假定我们项目中使用到了activemq,当我们项目pom中依赖activemq的starter时不定义version信息时,默认使用的是父类pom的版本,这和类的子类方法覆盖父类方法类似。
3.项目为web时,需要添加start-web依赖,此时springboot会引入Tomcat默认配置。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
4.我们编写SpringBoot项目的启动类
使用@SpringBootApplication注解标识SpringBoot项目的启入口
@SpringBootApplication
调用SpringApplication类的run方法
SpringApplication.run(App.class, args);
package springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* Hello world!
*
*/
@SpringBootApplication
public class App
{
public static void main( String[] args )
{
SpringApplication.run(App.class, args);
}
}
5.编写Controller类
使用@RestController注解标识Controller层,注解@RequestMapping指定url.(还可以使用@GetMapping和@PostMapping注解)
package springboot;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@RequestMapping(value = "/hello")
public static String hello(){
return "hello world!";
}
}
6.找到App程序入口,启动项目。
可以看到,项目在8080端口启动,访问http://localhost:8080/hello即访问。