springboot学习笔记-1 第一个springboot示例

来源:互联网 发布:北航网络教育平台 编辑:程序博客网 时间:2024/06/06 06:45

 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);     }}
复制代码

  当看到控制台出现以下界面的时候,代表springboot启动成功:

  打开浏览器,输入url:http://localhost:8080/user/1,看到如下界面:

  访问成功.

  注意对于Application类来说,有两个新元素值得注意.其一是@EnableAutoConfiguration,其二是SpringApplication类,它们都由springboot框架提供.在SpringApplication的run方法执行,springboot的AutoConfigure将会检测到这是一个web应用,随后用其内置的tomcat插件运行此web应用.注意在servletContext中配置的springmvc是默认的:

  DispatcherServlet匹配的路径(即servlet-mapping)为/*.

    @componentScan如果不写参数,那么默认的扫描路径为同一个包下.

  • SpringApplication
加油
原创粉丝点击