1.概述
如今,Web应用程序通常分为两个组件-前端和后端。
随着诸如Angular和React之类的前端技术的日益普及,后端功能通常作为RESTful API公开。
在本教程中,我们将使用Spring Boot创建RESTful API。 同时,我们将使用Spring Data MongoDB通过连接到MongoDB在我们的应用程序中提供持久性支持。
2.先决条件
我们需要一套标准工具:
- Java 8或更高版本
- 生成工具(Maven或Gradle)
- IDE(IntelliJ或Eclipse)
我们将结合使用Java 8, Gradle和IntelliJ进行实现。
为了快速创建Spring Boot应用程序,我们将使用Spring Initializr 。 另外,我们将安装和配置Mongo DB 。
3.申请
让我们为用户注册应用程序创建RESTful API。
为简单起见,我们将仅添加功能来执行CRUD(创建,读取,更新和删除)操作。
创建Spring Boot应用程序后,我们将使用MongoDB配置详细信息创建application.properties文件:
spring.data.mongodb.database=springboot_mongo_db
3.1。 实体
首先,我们将使用基本属性(如firstName , lastName和email)创建User实体:
@Getter
@Setter
public class User {
@Id
private String id ;
private String firstName ;
private String lastName ;
private String email ;
private String phone ;
private String address ;
}
在这里,我们使用@Id注释定义标识符。
同时,我们使用了由Lombok项目提供的@Getter和@Setter批注自动创建吸气剂/设置器。
3.2。 资料库
然后,我们将创建UserRepository接口,该接口使用Spring Data提供的MongoRepository在数据库上提供基本操作:
public interface UserRepository extends MongoRepository < User , String > {
}
3.3。 服务
接下来,我们将创建一个服务类,为基本的CRUD操作提供业务逻辑。
为此,让我们创建Registration接口来定义抽象:
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 ;
}
然后,我们将创建RegistrationImpl类以实现Registration接口:
@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 );
}
}
}
请注意,我们已经使用@Service批注将RegistrationImpl类声明为Spring Boot的服务。 另外,我们使用@Autowired批注注入UserRepository依赖项。
3.4。 控制者
现在我们已经准备好实体,存储库和服务,我们将创建RegistrationController类以公开API:
@RestController
public class RegistrationController {
@Autowired
private RegistrationImpl registrationImpl ;
}
在这里,我们使用@RestController批注将其声明为RESTful API控制器。
首先,我们将添加一个方法registerUser来注册用户(CREATE):
@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(READ)搜索用户:
@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方法来删除用户(DELETE):
@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。 验证方式
接下来,我们将使用hibernate-validator将bean验证功能添加到我们的API中。
首先,我们将依赖项添加到build.gradle中 :
compile group: 'org.hibernate' , name: 'hibernate-validator' , version: '5.0.0.Final'
然后,我们将向User实体添加一些注释,例如@NotNull和@Email 。
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 ;
}
接下来,我们将使用ValidatingMongoEventListener作为主类的Bean注册- 应用 :
@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 );
}
}
最后,我们将在RegistrationController中修改registerUser方法以验证User对象:
@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"}'
在这里,我们没有提供firstName , lastName和phone 。 因此,响应将是:
{ "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整合
到目前为止,我们已经使用curl来请求我们的API。 现在,我们将使用Springfox 为我们的API集成Swagger 2文档 。
我们所需要的只是在build.gradle中添加Springfox依赖项 :
compile "io.springfox:springfox-swagger2:2.9.2"
compile 'io.springfox:springfox-swagger-ui:2.9.2'
然后,我们将使用@ EnableSwagger2注释对主类进行注释:
@EnableSwagger2
@SpringBootApplication
public class Application {
// ...
}
而已! 我们的API规范已准备就绪,可以从http:// localhost:8080 / swagger-ui.html访问 。
4。结论
在本教程中,我们使用SpringBoot和Spring Data Mongo DB为用户注册应用创建了RESTful API。
另外,我们使用Project Lombok减少了Swagger 2文档的样板代码和Springfox API。
整个代码实现都可以在Github上获得
请让我知道您对此的想法!
谢谢阅读。
From: https://dev.to/smartyansh/create-restful-apis-using-spring-boot-mongo-db-6cf