Hello,Springboot!
1.maven构建项目
<?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> <parent> <!-- spring-boot-starter-parent 是一个特殊的Starter , 提供了一些Maven 的默认配置,同时还提供了--> <!-- dependency-management,可以便开发者在引入其他依赖时不必输入版本号,方便依赖管理。--> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.4.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.example</groupId> <artifactId>demo</artifactId> <version>0.0.1-SNAPSHOT</version> <name>demo</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
2.启动类
// @EnableAutoConfiguration 注解表示开启自动化配直。由于项目中添加了spring-boot-starterweb // 依赖, 因此在开启了自动化配置之后会自动进行Spring 和SpringMVC 的配置。 // 在Java 项目的main 方法中,通过SpringApplication 中的m 方法启动项目。第一个参数传入 // App.class ,告诉Spring 哪个是主要组件。第二个参数是运行时输入的其他参数。 @EnableAutoConfguration public class App { public static void main (String [] args) { SpringApplication.run(App.class, args ); } }
3.编写第一个Controller
@RestController public class HelloController { @GetMapping("/hello") public String hello(){ return "hello Spring Boot"; } }
4.需要将Controller注册到springmvc
给启动类添加 @ComponentScan 注解进行包的扫描,
Springboot提供了 @SpringBootApplication 替换 @EnableAutoConfiguration 和 @ComponentScan
@SpringBootApplication public class App { public static void main (String [] args) { SpringApplication.run(App.class, args ); } }
5.启动项目
直接运行App类的Main方法,然后浏览器地址输入:localhost:8080/hello。至此HelloWorld程序运行结束.