SpringBoot注解模式

项目使用的Maven管理依赖,

创建项目以后,需要引入springboot的相关依赖:

<properties>
    <!-- spring boot -->
    <spring.boot.version>2.1.0.RELEASE</spring.boot.version>
</properties>

<dependencies>
    <!-- springboot 启动依赖 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
        <version>${spring.boot.version}</version>
    </dependency>

    <!-- springboot web依赖 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <version>${spring.boot.version}</version>
    </dependency>
</dependencies>

创建项目的目录结构:

       

       这里的User就是一个实体类,这里不详述。

       UserController的代码:

package com.springboot.controller;

import com.springboot.model.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController   // RestController:这是一个Controller类,同时响应数据为Json格式。
@RequestMapping(value = "/user") 
public class UserController {

    @RequestMapping(value = "/findUsers", method = RequestMethod.GET)
    public List<User> findUsers() {
        List<User> list = new ArrayList<User>(10);
        list.add(new User(1, "0001", "Tom", "Tom", 1));
        return list;
    }
}

       下面是springboot的入口程序代码:

package com.springboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

@EnableWebMvc   // EnableWebMvc:默认启用WebMvc模式。
@SpringBootApplication    // springboot的主程序
public class SpringBootMain {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootMain.class);
    }
}

     特别提醒:springboot程序SpringBootmMain需放controller、model等文件夹的统计目录下,因为在springboot程序启动时会自动扫描入口程序的统计目录下的注解。

    浏览器访问,返回的结果数据:

    

发布了44 篇原创文章 · 获赞 36 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/ailian_f/article/details/89449982