SpringBoot入门(约定优先于配置)
0)创建一个maven项目
1)通过Pom建立springboot支持
<?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.boot</groupId> <artifactId>springboot_01</artifactId> <version>1.0-SNAPSHOT</version> <!-- springboot的核心启动器 --> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.0.RELEASE</version> </parent> <dependencies> <!-- spingboot的web模块包含tomcat和springmvc --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- junit --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <scope>test</scope> </dependency> </dependencies> </project>
2)万年不变的hello word
package com.boot.controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * @author: 肖德子裕 * @date: 2018/11/06 9:30 * @description: springboot入门 * RestController相当于springmvc的Controller+ResponseBody */ @RestController public class HelloController { @RequestMapping("/hello") public String hello(){ return "hello spring boot"; } }
3)一个全局配置文件
#全局配置文件,修改springboot项目的默认配置值 #http://docs.spring.io/spring-boot/docs/2.1.0.RELEASE/reference/htmlsingle/#common-application-properties #端口号 server.port=8081
可以设置启动时的图标(banner.txt)
http://patorjk.com/software/taag
4)springboot通过一个类启动
package com.boot.controller; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * @author: 肖德子裕 * @date: 2018/11/06 9:37 * @description: 项目启动 * SpringBootApplication:指定这是一个springboot的应用程序 * SpringBootApplication相当于springmvc的Configuration+EnableAutoConfiguration+ComponentScan * Configuration:配置注解 * EnableAutoConfiguration:启动自动配置 * ComponentScan:扫描配置 */ /** * 自动配置原理:从classpath中搜寻所有的META-INF/spring.factories配置文件; * 并将其中EnableAutoConfiguration对应的配置项通过反射实例化为对应的标注了@Configuration的IOC容器配置类; * 然后汇总并加载到spring框架的IOC容器。 */ @SpringBootApplication public class App { public static void main(String[] args) { //SpringApplication用于从main启动spring应用的类 SpringApplication.run(App.class,args); } }