
[英]Issues in Enabling the swagger 2 in Spring Boot java application
[英]@Document Annotation for Collection Name in MongoDb for Java models Generated through Swagger in Spring boot Application
我正在遵循的步骤
我为我的微服务编写 API 合同和定义模型的 Swagger 文件
现在,我在我的 Spring 启动应用程序中使用 Swagger 代码生成依赖项,通过从 URL 读取 Swagger 来生成模型,该 URL 托管在“mvn install”上我的应用程序的目标(pom.xml 中提到的输出目录)目录中。
对于 Swagger 文件中的每个定义,将在我的应用程序的目标目录中生成一个模型类。
现在我使用 mongoDB 作为模型保存为集合的数据库。
需要给 @Document(value = "collection-name") - 动态地用于模型类。
由于模型类是通过 Swagger codegen 生成的,因此无法编辑这些,
那么如何为我想保存在数据库中的定义维护动态名称有没有办法通过 Swagger Contract 来定义它?
前段时间我一直在努力解决同样的问题, 一些解决方案包括对生成的文件进行后处理。
但是,出于安全考虑,将 MongoDB 模型暴露给 API 可能并不完全正确。 一个有趣的方法是简单地使用 Mappers 并将 DTO 概念应用于自动生成的模型类。
例如:
假设您在 MongoDB 中有一个用户集合,以及一个用于检索用户的 API。
components:
schemas:
User:
type: object
properties:
id:
type: string
name:
type: string
Swagger 自动生成的类是这样的:
package api;
@ApiModel()
@Validated
public class User {
@JsonProperty("id")
private String id = null;
@JsonProperty("name")
private String name = null;
}
您还将拥有“标准”用户模型类:
package model;
@Document(collection = "users")
public class User {
@Id
private String id;
@NotNull
private String name;
@NotNull
private String password;
}
例如,请注意密码字段不包含在 API 定义中。
然后我们将拥有典型的用户存储库:
public interface UserRepository extends MongoRepository<User, String> { }
现在我们必须实现映射器,使用MapStruct非常简单:
@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface UserMapper {
api.User map(model.User user);
}
您可以广泛自定义映射哪些信息以及如何映射信息。
唯一剩下的是控制器:
@Controller
public class MyController implements MyApi {
@Inject
UserMapper mapper;
@Autowired
private UserRepository repository;
@GetMapping("/api/v1.0/users")
public ResponseEntity<List<api.User>> getAllUsers() {
List<api.User> users = new ArrayList<>();
repository.findAll().forEach(user -> users.add(mapper.map(user)));
return new ResponseEntity(users, HttpStatus.OK);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.