springboot入门第二篇之Helloworld

来源:互联网 发布:淘客网站源码建立 编辑:程序博客网 时间:2024/05/29 16:06

上一节提到,Springboot简化了配置文件,降低了spring的入门,使得新手可以快速搭建框架。

下面我们通过编写一个Hello World来说明步骤,主要分为4步:

    1 新建一个Maven-java工程

    2 在pom.xml文件中添加Maven依赖

    3 编写springboot启动项

    4 运行程序

1搭建Maven工程

这个步骤在上一篇博客中有介绍,这里就不在详细的讲了,新建一个Maven web Project工程(建Maven Java Project工程也可以),工程名为spring-boot-helloworld。

2加入依赖

在pom.xml文件中引入sp接着,由于我们日常开发的是web应用,需要在pom.xml文件中引入spring-boot-starter-web,它包含了spring web MVC和tomcat等web开发的特性。

<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>1.3.3.RELEASE</version></parent>

接着,由于我们日常开发的是web应用,需要在pom.xml文件中引入spring-boot-starter-web,它包含了spring web MVC和tomcat等web开发的特性。

<dependencies>      <dependency>          <groupId>org.springframework.boot</groupId>           <artifactId>spring-boot-starter-web</artifactId>          </dependency></dependencies>

项目运行的时候,不需要通过tomcat来启动,直接在Main函数里面启动,需要添加plugin,否则无法启动,如果使用的Maven的spring-boot:run启动的则不需要配置。

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

3编写启动项

在main方法里面编写启动项,然后在启动类里面配置注解标签,有RestController和SpringBootApplication。其中@SpringBootApplication申明让Springboot自动给程序进行必要的配置,等价于默认使用@Configuration,@EnableAutoConfiguration和ComponentScan,@RestController返回json字符串的数据,直接可以编写RESTFul的接口;(注意,在真正做项目的时候,Controller层的代码是放在单独的一个包里的,这里为了简单,写在了一块)

代码如下:

@RestController@SpringBootApplicationpublic class App {    @RequestMapping("/")  public String hello(){    return "Hello world!";  }    public static void main(String[] args) {          SpringApplication.run(App.class, args);  }}

4运行程序

程序的运行有两种方式,下面一一介绍。

第一种是右键Run as ->Java Application。然后打开浏览器输入:http://127.0.0.1:8080,就可以看到hello world!

第二种方式是右键project->run as ->Maven build,在Goals里输入spring-boot:run,然后Apply,z最后点击run。

 

特别注意

JDK的版本问题会导致程序启动不成功。