Spring Boot基础教程:构建spring-rest-curd + 单元测试

1. 简介

在学习了如何快速创建一个Spring Boot项目和简单使用Spring Boot搭建web项目,接下来要学习的是如何将在mvc模式中使用,本文完成了一个RESTful API + curd的简单例子,并使用TestRestTemplate来进行junit测试。

2. 环境

使用环境参考Spring Boot基础教程汇总中的讲解:详情请点击

3. 快速入门

项目结构

这里写图片描述
上图是Spring Boot推荐的典型结构,通常建议将应用的main类(Application)放到其他类所在的包的顶层(root package),并将@EnableAutoConfiguration注解到你的main类上,其作用是开启自动配置。

The second class-level annotation is @EnableAutoConfiguration. This annotation tells Spring Boot to “guess” how you will want to configure Spring, based on the jar dependencies that you have added. Since spring-boot-starter-web added Tomcat and Spring MVC,the auto-configuration will assume that you are developing a web application and setup Spring accordingly.Starters and Auto-Configuration.

简要概括,@EnableAutoConfiguration会根据添加的jar包对Spring进行相应的设置,比如你加载了spring-boot-starter-web,则会开启Spring Mvc的自动配置,在日志中,可以看到加载了tomcat和spring mvc。想了解更多关于@EnableAutoConfiguration注解,请看一下这篇文章:springboot EnableAutoConfiguration
采用root package的结构,就可以使用@ComponentScan而不需要指定basePackage属性,因为默认从Appliacation由上向下,逐层扫描加了注解的类。

引入依赖

无特别引入其他依赖,该介绍可参考文章创建第一个Spring Boot应用之Hello World中的相关说明。

代码详解

User实体定义:

public class User {

    private long id;
    private String name;
    private String country;

    public User(long id, String name, String country) {
        this.id = id;
        this.name = name;
        this.country = country;
    }

    public User() {

    }

    // 省略setter和getter 

}

UserService定义:实现简单的curd

@Service
public class UserServiceImpl implements UserService{
   

    private static List<User> users;

    static {
        users = initUser();
    }

    private static List<User> initUser() {
        List<User> users = new ArrayList<>(10);
        users.add(new User(1L,"Mac","USA"));
        users.add(new User(2L,"HuaWei",
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值