使用Spring Boot + Mongodb创建RESTful API

1. Overview

如今,Web应用程序通常分为两个组件-前端和后端。

随着诸如Angular和React之类的前端技术的日渐普及,后端功能通常作为RESTful API公开。

In this tutorial, we'll create RESTful APIs using Spring Boot. At the same time, we'll use Spring Data MongoDB to provide persistence support in our App by connecting to MongoDB.

2. Prerequisites

我们需要一套标准工具:

  • Java 8或更高版本生成工具(Maven或Gradle)IDE(IntelliJ或Eclipse)

We'll use a combination of Java 8, Gradle and IntelliJ for our implementation.

To quickly create the Spring Boot application, we'll use Spring Initializr. Also, we'll install and configure Mongo DB.

3. Application

让我们为用户注册应用程序创建RESTful API。 为简单起见,我们仅添加功能来执行CRUD(创建,读取,更新和删除)操作。

创建Spring Boot应用后,我们将创建application.properties带有MongoDB配置详细信息的文件:

spring.data.mongodb.database=springboot_mongo_db

3.1. Entity

首先,我们将创建用户具有基本属性的实体,例如名字,姓,and 电子邮件:

@Getter
@Setter
public class User {
    @Id
    private String id;

    private String firstName;
    private String lastName;
    private String email;
    private String phone;
    private String address;
}

Here, we've used @Id annotation to define the identifier.

At the same time, we've used @Getter and @Setter annotations provided by the Project Lombok to create getters/setters automatically.

3.2. Repository

Then, we'll create the UserRepository interface that provides basic operations on the database using Spring Data provided MongoRepository:

public interface UserRepository extends MongoRepository<User, String> {
}

3.3. Service

接下来,我们将创建一个服务类,为基本的CRUD操作提供业务逻辑。

为此,我们来创建注册定义抽象的接口:

public interface Registration<ID, USER> {
    USER registerUser(USER user) throws Exception;

    USER getUser(ID userId) throws Exception;

    USER updateUser(USER user) throws Exception;

    void deleteUser(ID userId) throws Exception;
}

然后,我们将创建注册Impl类来实现注册接口:

@Service
public class RegistrationImpl implements Registration<String, User> {
    @Autowired
    private UserRepository userRepository;

    @Override
    public User registerUser(User user) throws Exception {
        user = userRepository.save(user);
        return user;
    }

    @Override
    public User getUser(String userId) throws Exception {
        User user = userRepository.findById(userId);
        return user;
    }

    public List<User> getAllUser() throws Exception {
        List<User> users = userRepository.findAll();
        return users;
    }

    @Override
    public User updateUser(User user) throws Exception {
        user = userRepository.save(user);
        return user;
    }

    @Override
    public void deleteUser(String userId) throws Exception {
        if (userId == null) {
            throw new Exception("user id is null");
        } else {
            userRepository.delete(userId);
        }
    }
}

Note that we've used @Service annotation to declare the RegistrationImpl class as a service for Spring Boot. Also, we've used @Autowired annotation to inject the UserRepository dependency.

3.4. Controller

现在我们已经准备好实体,存储库和服务,我们将创建RegistrationController类公开API:

@RestController
public class RegistrationController {
    @Autowired
    private RegistrationImpl registrationImpl;
}

Here, we've used @RestController annotation to declare it as a RESTful API controller.

首先,我们将添加一个方法registerUser注册用户(创建):

@PostMapping(path = "/registerUser")
public ResponseEntity registerUser(@RequestBody User user) throws Exception {
    HashMap<String, Object> resp = new HashMap<>();
    registrationImpl.registerUser(user);
    resp.put("user", user);
    return new ResponseEntity<>(resp, HttpStatus.OK);
}

瞧,我们已经准备好使用第一个RESTful API来注册用户。

让我们使用以下curl命令尝试一下:

curl -X POST "http://localhost:8080/registerUser" -H "Content-Type: application/json" \
-d '{"email": "xyz@email.com", "firstName": "norman", "lastName": "lewis", "phone": "90909090"}'

然后,我们添加一个方法getUser通过ID搜索用户(读取):

@GetMapping("/getUser" )
public ResponseEntity getUser(@RequestParam("id") String id) throws Exception {
    User user = registrationImpl.getUser(id);
    return new ResponseEntity<>(user, HttpStatus.OK);
}

因此,我们可以使用curl来读取用户:

curl -X GET "http://localhost:8080/getUser?id=5e0a0a393844b64a1548c4d9"

同样,我们可以定义一个方法getAllUser获取所有用户:

@GetMapping("/getAllUser" )
public ResponseEntity getAllUser() throws Exception {
    List<User> users = registrationImpl.getAllUser();
    return new ResponseEntity<>(users, HttpStatus.OK);
}

然后,我们将添加一个方法updateUser更新用户(UPDATE):

@PutMapping(path = "/updateUser")
public ResponseEntity updateUser(@RequestParam("id") String id, @RequestBody User user) 
throws Exception {
    HashMap<String, Object> resp = new HashMap<>();
    registrationImpl.updateUser(user);
    resp.put("user", user);
    return new ResponseEntity<>(resp, HttpStatus.OK);
}

最后,让我们添加一个方法deleteUser删除用户(删除):

@DeleteMapping("/deleteUser")
public ResponseEntity deleteUser(@RequestParam("id") String id) throws Exception {
    registrationImpl.deleteUser(id);
    HashMap<String,String> resp = new HashMap<>();
    resp.put("message", "User is successfully deleted");
    return new ResponseEntity<>(resp, HttpStatus.OK);
}

3.5. Validation

Next, we'll add the feature of bean validations to our APIs using hibernate-validator.

首先,我们将依赖项添加到build.gradle:

compile group: 'org.hibernate', name: 'hibernate-validator', version: '5.0.0.Final'

Then, we'll add a few annotations like @NotNull and @Email to the User entity.

public class User {
    // ...

    @NotNull(message = "First Name is mandatory")
    private String firstName;

    @NotNull(message = "Last Name is mandatory")
    private String lastName;

    @NotNull(message = "Email is mandatory")
    @Email(message = "Not valid email")
    @Indexed(unique=true)
    private String email;

    @NotNull(message = "Phone Number is mandatory")
    private String phone;    
}

Next, we'll use the ValidatingMongoEventListener to register as a bean in the main class - Application:

@SpringBootApplication
public class Application {
    @Bean
    public ValidatingMongoEventListener validatingMongoEventListener() {
        return new ValidatingMongoEventListener(validator());
    }

    @Bean
    public LocalValidatorFactoryBean validator() {
        return new LocalValidatorFactoryBean();
    }

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

最后,我们将修改registerUser中的方法RegistrationController验证用户对象:

@PostMapping(path = "/registerUser")
public ResponseEntity registerUser(@RequestBody User user) throws Exception {
    HashMap<String, Object> resp = new HashMap<>();
    try {
        registrationImpl.registerUser(user);
    } catch (ConstraintViolationException e) {
        HashMap<String, String> messages = new HashMap<>();
        e.getConstraintViolations().stream().forEach(constraintViolation -> {
            messages.put(
                    constraintViolation.getPropertyPath().toString(),
                    constraintViolation.getMessage());
        });
        resp.put("error", true);
        resp.put("messages", messages);
    }
    resp.put("user", user);
    return new ResponseEntity<>(resp, HttpStatus.OK);
}

而已! 我们准备检查验证:

curl -X POST "http://localhost:8080/registerUser" -H "Content-Type: application/json" -d '{"email": "xyz@email.com"}'

在这里,我们没有提供名字,姓,and 电话. So,the response will be:

{"messages":{"firstName":"First Name is mandatory","lastName":"Last Name is mandatory","phone":"Phone Number is mandatory"},"error":true,"user":{"id":null,"firstName":null,"lastName":null,"email":"xyz12@email.com","phone":null,"address":null}}

3.6. Swagger Integration

So far, we've used curl to request our APIs. Now, we'll integrate 小号wagger 2 documentation for our APIs using Springfox.

我们所需要做的就是在其中添加Springfox依赖项build.gradle:

compile "io.springfox:springfox-swagger2:2.9.2"
compile 'io.springfox:springfox-swagger-ui:2.9.2'

然后,我们将使用@ EnableSwagger2注释对主类进行注释:

@EnableSwagger2
@SpringBootApplication
public class Application {

    // ...
}

That's it! Our API specifications are ready and are accessible at http://localhost:8080/swagger-ui.html.

4. Conclusion

在本教程中,我们使用SpringBoot和Spring Data Mongo DB为用户注册应用创建了RESTful API。 此外,我们使用Project Lombok减少了Swagger 2文档的样板代码和Springfox API。

The entire code implementations are available over on Github

请让我知道您对此的想法! 谢谢阅读。

from: https://dev.to//smartyansh/create-restful-apis-using-spring-boot-mongo-db-6cf

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值