[springboot]-yml读入

本文探讨了YML配置文件在Spring Boot项目中的应用,包括驼峰命名法与下划线命名法的使用,以及如何在代码中映射YML配置。详细介绍了Map和List类型的数据在YML配置中的表示方法,以及在Java实体类中的对应声明。

List contactList

在这里插入图片描述

Map<String, List<String>>

menu:
  delete-top-menu: ['10','12','15','16','20','23','27','28','29','30','31','33','34','35','37','38','39','40','41','42','44','47','48','49']
  delete-second-menu: {"25": ['2502','2503','2505','2506'],"22222": ["1111"]}

yml的驼峰下划线

属性名命名可以使用驼峰命名法,也可以使用-或者_,比如用户名可以是userName,user-name,USER_NAME,意思都是一样的

句子解析备注
@Valueyml 中是user-name ,代码中必须是@Value(“${user-name}”)宽松匹配
@ConfigurationPropertiesyml 中是user-name ,代码中String userName严格匹配
link

Map ==> value 为实体

yml
simple:
  config:
    refresh-enabled: true
    data:  
      bmw:
        engine: iron
        chair: leather
        price: 999999
      xiali:
        engine: plastic
        chair: plastic
        price: 10001   
java
@ConfigurationProperties("simple.config")
@Component
@RefreshScope
@Data
public class CarProperties {


    private Map<String, Config> data = new HashMap();


    @Data
    public static class Config {

        private String chair;

        private String engine;

        private Integer price;
    }

}

springBoot配置文件yml字符串换行问题

link
在这里插入图片描述

你的实体

在这里插入图片描述
@Component不能少的

如何弄Map和List

map


上面的rateLimit就是map接受的
在这里插入图片描述

List

在这里插入图片描述

private List<Integer> li;

在这里插入图片描述

List<Map>怎么弄

在这里插入图片描述

    private List<Map> valueMapList;

在这里插入图片描述

在这里插入图片描述

如果您觉得我的付出对您有帮助,还请关注+点赞哦

<think>我们被要求使用Spring Boot将图片存储到MongoDB中。根据引用内容,我们可以使用MongoDB的GridFS来存储文件(包括图片)。GridFS是MongoDB的一种存储机制,用于存储大于16MB的文件,它将大文件分割成多个小块进行存储。 步骤: 1. 添加依赖:在pom.xml中添加Spring Boot的MongoDB starter依赖。 2. 配置MongoDB连接:在application.properties或application.yml中配置MongoDB的连接信息。 3. 创建GridFS配置类:用于创建GridFSBucket的Bean,以便在操作GridFS时使用。 4. 编写服务层代码:实现图片的上传、下载等功能。 详细步骤: 第一步:添加依赖 在pom.xml中添加以下依赖(版本根据实际情况选择,这里使用引用中提到的2.1.5.RELEASE,但实际项目中建议使用与Spring Boot版本匹配的依赖版本): ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> <version>2.1.5.RELEASE</version> <!-- 可以省略版本号,由Spring Boot父项目统一管理 --> </dependency> ``` 第二步:配置MongoDB连接 在application.properties中配置: ```properties spring.data.mongodb.host=localhost spring.data.mongodb.port=27017 spring.data.mongodb.database=test # 数据库名 ``` 第三步:创建GridFS配置类 创建一个配置类,用于提供GridFSBucket的Bean。这样我们可以在其他地方注入GridFSBucket来操作文件。 例如: ```java import com.mongodb.client.MongoClient; import com.mongodb.client.gridfs.GridFSBucket; import com.mongodb.client.gridfs.GridFSBuckets; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class MongoConfig { @Value("${spring.data.mongodb.database}") private String db; @Bean public GridFSBucket getGridFSBucket(MongoClient mongoClient) { MongoDatabase database = mongoClient.getDatabase(db); return GridFSBuckets.create(database); } } ``` 第四步:编写服务层代码 创建一个服务类,用于处理图片的上传和下载。 上传图片示例: ```java import com.mongodb.client.gridfs.GridFSBucket; import com.mongodb.client.gridfs.GridFSUploadStream; import com.mongodb.client.gridfs.model.GridFSUploadOptions; import org.bson.Document; import org.bson.types.ObjectId; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; @Service public class FileStorageService { @Autowired private GridFSBucket gridFSBucket; public String storeFile(MultipartFile file) throws IOException { // 设置文件的元数据(可选) Document metaData = new Document(); metaData.put("contentType", file.getContentType()); metaData.put("size", file.getSize()); GridFSUploadOptions options = new GridFSUploadOptions() .chunkSizeBytes(1024 * 1024) // 设置块大小,可选 .metadata(metaData); // 打开上传流 GridFSUploadStream uploadStream = gridFSBucket.openUploadStream(file.getOriginalFilename(), options); // 写入文件内容 uploadStream.write(file.getBytes()); // 完成上传 uploadStream.close(); // 返回文件在GridFS中的唯一ID(ObjectId) return uploadStream.getObjectId().toString(); } } ``` 注意:上面的代码中,我们使用了GridFSUploadStream来上传文件。另一种方式是使用Spring Data MongoDB提供的GridFsTemplate,但这里我们直接使用GridFSBucket。 使用GridFsTemplate的方式(另一种可选方式): 如果你更倾向于使用Spring Data MongoDB提供的GridFsTemplate,可以这样: 首先,确保已经配置了GridFsTemplate的Bean(Spring Boot会自动配置,但如果你需要自定义,可以自己创建Bean): ```java @Bean public GridFsTemplate gridFsTemplate(MongoDatabaseFactory dbFactory, MongoConverter converter) { return new GridFsTemplate(dbFactory, converter); } ``` 然后在服务中注入GridFsTemplate: ```java @Autowired private GridFsTemplate gridFsTemplate; public String storeFile(MultipartFile file) throws IOException { ObjectId objectId = gridFsTemplate.store(file.getInputStream(), file.getOriginalFilename(), file.getContentType()); return objectId.toString(); } ``` 这里我们提供了两种方式,可以根据需要选择。 第五步:编写控制器 创建一个控制器来处理上传请求。 ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; @RestController public class FileUploadController { @Autowired private FileStorageService fileStorageService; @PostMapping("/upload") public String uploadFile(@RequestParam("file") MultipartFile file) throws IOException { return fileStorageService.storeFile(file); } } ``` 这样,当用户通过POST请求访问/upload并上传文件时,文件将被存储到MongoDB的GridFS中,并返回文件的ID。 注意事项: 1. 确保MongoDB服务已经启动。 2. 上传大文件时,需要考虑内存使用情况,避免一次性读取整个文件到内存。上面的示例中使用了file.getBytes(),对于大文件,可以使用流式上传,避免将整个文件读入内存。 对于大文件,我们可以使用InputStream和流式上传: ```java public String storeLargeFile(MultipartFile file) throws IOException { GridFSUploadOptions options = new GridFSUploadOptions() .chunkSizeBytes(1024 * 1024) .metadata(new Document("contentType", file.getContentType())); try (InputStream inputStream = file.getInputStream()) { ObjectId objectId = gridFSBucket.uploadFromStream(file.getOriginalFilename(), inputStream, options); return objectId.toString(); } } ``` 这样,文件会被分块读取和上传,减少内存占用。 以上是使用Spring Boot将图片存储到MongoDB的详细步骤。 §§相关问题§§ 1. 如何从MongoDB GridFS中下载图片? 2. 如何删除存储在GridFS中的图片? 3. 如何更新存储在GridFS中的图片? 4. 如何获取存储在GridFS中的图片的元数据信息? 5. 使用GridFS存储图片有哪些优缺点?</think>### Spring Boot 存储图片到 MongoDB 的完整指南 使用 Spring Boot 将图片存储到 MongoDB 主要通过 MongoDB 的 **GridFS** 实现,以下是详细步骤: --- ### 第一步:添加依赖 在 `pom.xml` 中添加 MongoDB 依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> <version>3.1.0</version> <!-- 使用最新稳定版 --> </dependency> ``` --- ### 第二步:配置 MongoDB 连接 在 `application.properties` 中配置: ```properties spring.data.mongodb.uri=mongodb://localhost:27017/testdb ``` --- ### 第三步:创建 GridFS 配置类 ```java import com.mongodb.client.gridfs.GridFSBucket; import com.mongodb.client.gridfs.GridFSBuckets; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.mongodb.client.MongoClient; @Configuration public class MongoConfig { @Bean public GridFSBucket gridFSBucket(MongoClient mongoClient) { return GridFSBuckets.create(mongoClient.getDatabase("testdb")); } } ``` --- ### 第四步:实现图片上传服务 ```java import com.mongodb.client.gridfs.GridFSBucket; import org.bson.types.ObjectId; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; @Service public class ImageService { private final GridFSBucket gridFSBucket; public ImageService(GridFSBucket gridFSBucket) { this.gridFSBucket = gridFSBucket; } public String uploadImage(MultipartFile file) throws IOException { // 创建元数据(可选) Map<String, String> metadata = new HashMap<>(); metadata.put("contentType", file.getContentType()); metadata.put("originalName", file.getOriginalFilename()); // 上传图片 ObjectId fileId = gridFSBucket.uploadFromStream( file.getOriginalFilename(), file.getInputStream(), new GridFSUploadOptions().metadata(new Document(metadata)) ); return fileId.toString(); // 返回文件ID } } ``` --- ### 第五步:实现图片下载服务 ```java public byte[] downloadImage(String fileId) { GridFSFindIterable files = gridFSBucket.find(Filters.eq("_id", new ObjectId(fileId))); GridFSFile file = files.first(); try (GridFSDownloadStream stream = gridFSBucket.openDownloadStream(file.getObjectId())) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); stream.transferTo(outputStream); return outputStream.toByteArray(); } } ``` --- ### 第六步:创建 REST 控制器 ```java import org.springframework.web.bind.annotation.*; import org.springframework.http.MediaType; @RestController @RequestMapping("/images") public class ImageController { private final ImageService imageService; public ImageController(ImageService imageService) { this.imageService = imageService; } // 上传图片 @PostMapping public String upload(@RequestParam("file") MultipartFile file) throws IOException { return imageService.uploadImage(file); } // 下载图片 @GetMapping(value = "/{id}", produces = MediaType.IMAGE_JPEG_VALUE) public byte[] download(@PathVariable String id) { return imageService.downloadImage(id); } } ``` --- ### 关键说明 1. **GridFS 原理** MongoDB 自动将大文件分割为 $256KB$ 的块(`fs.chunks` 集合),文件元数据存储在 `fs.files` 集合中[^1]。 2. **文件大小限制** - 默认支持最大 $16MB$ 的文件 - GridFS 支持任意大文件(如高清图片/视频) 3. **元数据扩展** 可在上传时添加自定义属性: ```java metadata.put("uploader", "user123"); ``` --- ### 测试示例 - **上传图片**: ```bash curl -F "file=@test.jpg" http://localhost:8080/images ``` 返回:`5f8d9a4c3d8e6b1a2c7b0e1f`(文件ID) - **下载图片**: ```bash http://localhost:8080/images/5f8d9a4c3d8e6b1a2c7b0e1f ``` --- ### 常见问题解决 1. **文件损坏**:确保使用 `GridFSDownloadStream` 而非直接读取字节 2. **性能优化**:对频繁访问的图片启用 MongoDB 分片 3. **内容类型**:通过 `metadata` 记录 `contentType` 确保正确渲染
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值