记我的Spring Boot第一行代码(一)

写在前面

SpringBoot遵循“习惯大于配置”的理念,简化了Maven配置,内嵌Servlet容器,从而无需部署WAR文件,可以自行选择Servlet容器。从而可以很容易创建一个独立运行,基于Spring框架的项目。在这我们选用的是Eclipse的集成开发环境。

1.构建Maven项目

    此时我们要做的就是修改prom.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>com.csdn</groupId>
  <artifactId>springboot_helloword</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <!-- SpringBoot项目 -->
  <parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.3.3.RELEASE</version>
	</parent>
	<dependencies>
	  <!-- SpringBoot web 组件  -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
	</dependencies>
</project>

2.添加测试控制器

    接着我们只需要在src/main/java的目录下新建一个测试类

package com.csdn.controller;

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 HelloController {
	@RequestMapping("/hello")
	public String index() {
		return "Hello world";
	}
	
	public static void main(String[] args) {
		SpringApplication.run(HelloController.class, args);
	}
}

3.结果展示

以Java Application形式运行,可以在控制台看到


在浏览器中输入http://localhost:8080/hello可以看到


4.注解解析

    这里面一共用到了三个注解,其中

        @RestController用于返回Json数据,直接可以编写Restful接口

        @EnableAutoConfiguration开启自动配置

        @RequestMapping用于配置url映射

可以看到SpringBoot确实很简单。

猜你喜欢

转载自blog.csdn.net/sinat_33010325/article/details/81048719