springboot学习笔记三
springboot,其设计的目的是为了简化spring框架的搭建和配置过程.从而使开发人员不再需要定义样板化的配置.下面是springboot的入门案例:它演示了利用springboot省去配置文件,然后通过运行Java程序,使得内置在springboot上面的tomcat运行,然后访问contoller的过程.
1.在eclipse在建立maven工程,配置pom.xml:pom.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.hlhdidi</groupId>
<artifactId>springboot1</artifactId>
<url>http://maven.apache.org</url>
<version>0.0.1-SNAPSHOT</version>
<!--默认继承父类去实现-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.0.RELEASE</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<!-- 添加springboot的web模板 -->
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
这里如果maven库中没有springboot对应的包的话,可能会下载很慢,耐心等吧...
2.建立controller
@RestController
@RequestMapping("/user")
public class FirstController {
@RequestMapping("/{id}")
public User testSpringBoot(@PathVariable("id") Integer id) {
User user=new User();
user.setUsername("hlhdidi");
user.setPassword(id+"");
System.out.println(user);
return user;
}
}
可以看出就是一个简单的controller,没有进行任何配置
3.建立Application类.通过运行main方法的方式,启动tomcat.
@EnableAutoConfiguration //标识该类开启springboot的配置.
@ComponentScan(basePackages={"com.xyy"})
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class);
}
}
打开浏览器,输入url:http://localhost:8080/user/1,看到如下界面:

访问成功.
注意对于Application类来说,有两个新元素值得注意.其一是@EnableAutoConfiguration,其二是SpringApplication类,它们都由springboot框架提供.在SpringApplication的run方法执行,springboot的AutoConfigure将会检测到这是一个web应用,随后用其内置的tomcat插件运行此web应用.注意在servletContext中配置的springmvc是默认的:
DispatcherServlet匹配的路径(即servlet-mapping)为/*.
@componentScan如果不写参数,那么默认的扫描路径为同一个包下.
SpringApplication
浙公网安备 33010602011771号