此文做记录交流,如有不当,还望指正。
开发使用springboot也有段时间了,最近发现很多之前用过的东西都已经遗忘,遂记录下来
创建空的maven项目

修改pom文件
<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.demo</groupId>
<artifactId>springboot-helloword</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>springboot-helloword</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.0.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>
编写启动类
package com.demo.springboot_helloword;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class HelloWordApplication {
public static void main(String[] args) {
SpringApplication.run(HelloWordApplication.class, args);
}
}
在启动类中添加REST方法
package com.demo.springboot_helloword;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class HelloWordApplication {
public static void main(String[] args) {
SpringApplication.run(HelloWordApplication.class, args);
}
@RequestMapping("/index")
public String index(){
return "HelloWord";
}
}
选中HelloWordApplication,右键选择run as,选择java application 或者 spring boot app 都可以,启动完成后在浏览器访问 http://localhost:8080/index 查看效果
@SpringBootApplication 注解
@SpringBootApplication是一个组合注解,包括@SpringBootConfiguration,@EnableAutoConfiguration,@ComponentScan及其他多个注解,是项目的启动注解
@SpringBootConfiguration:当前类是一个配置类,就像xml配置文件,而现在是用java配置文件,效果是一样的
@EnableAutoConfiguration:完成自动配置功能
@ComponentScan:用注解配置实现自动扫描,默认会扫描当前包和所有子包,和xml配置自动扫描效果一样,@Filter是排除了两个系统类
@RestController 注解
@RestController 本身也是一个组合注解,是由@Controller和@ResponseBody组成的
@Controller:标注此类是一个controller
@ResponseBody:标注一个contrller中的方法直接把数据写到ResponseBosy而不是返回一个页面。
@RequestMapping 注解
@RequestMapping是用来指定请求路径的,既可以作用在类上也可以作用在方法上,如果作用在类上则表示此路径为请求父路径
spring-boot-starter-parent
SpringBoot父依赖,配置后可使用SpringBoot依赖管理
spring-boot-starter-web
SpringBoot web 集成了spring mvc,RESTFUL,所需容器等
网友评论