SpringBoot?MongoCustomConversions自定義轉(zhuǎn)換方式
SpringBoot MongoCustomConversions自定義轉(zhuǎn)換
主要講述如何將mongo查詢語(yǔ)句出來(lái)的東西轉(zhuǎn)換成某個(gè)modelMongoTemplate.find(new BasicQuery(obj),XXX.class)
添加配置類
重新定義一下 MongoTemplate
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.core.convert.MongoCustomConversions;
// 該類的目的是把自定義編寫的轉(zhuǎn)換類 注入 MongoTemplate 中
@Configuration
public class MongoConfig{
@Autowired
MongoDbFactory factory;
@Bean //注冊(cè)客制化轉(zhuǎn)換 添加自定義轉(zhuǎn)換類(樓主以TestConverter為列,具體編寫跳轉(zhuǎn)“編寫自定義轉(zhuǎn)換類”)
public MongoCustomConversions customConversions() {
List<Converter<?,?>> converters = new ArrayList<Converter<?,?>>();
converters.add(new TestConverter());
return new MongoCustomConversions(converters);
}
@Bean
public MongoTemplate mongoTemplate() throws Exception {
MongoTemplate mongoTemplate = new MongoTemplate(factory);
MappingMongoConverter mongoMapping = (MappingMongoConverter) mongoTemplate.getConverter();
mongoMapping.setCustomConversions(customConversions()); // tell mongodb to use the custom converters
mongoMapping.afterPropertiesSet();
return mongoTemplate;
}
}編寫自定義轉(zhuǎn)換類
import org.bson.Document;
import org.springframework.core.convert.converter.Converter;
public class TestConverter implements Converter<Document, MaxtqReport> {
/**
* @param source : mongo中查詢出的內(nèi)容
* @return Test : 我們需要轉(zhuǎn)換的目標(biāo)類
*/
@Override
public Test convert(Document source) {
Test result = new Test();
result.setId(source.getObjectId("_id").toString());
result.setContent(content);
//自定義 code...
return result;
}
}業(yè)務(wù)流程的代碼塊
@Autowired // MongoTemplate 的創(chuàng)建用自動(dòng)注入
MongoTemplate template;
// 這里主要是介紹一下 業(yè)務(wù)流程中如何使用
// 這里是一個(gè)按手機(jī)號(hào)查詢案例
public void test(String mobile){
BasicDBList basicDBList = new BasicDBList();
if (StringUtils.isNotBlank(mobile)) {
// 添加查詢參數(shù)
basicDBList.add(new BasicDBObject("mobile", param.mobile));
}
Document obj = new Document();
obj.put("$and", basicDBList);
//創(chuàng)建查詢對(duì)象
Query query = new BasicQuery(obj);
// 此處會(huì)調(diào)用我們自定義的轉(zhuǎn)換
List<Test> test = this.template.find(query, Test.class)
}SpringBoot 自定義轉(zhuǎn)換器
基本介紹
SpringBoot 在響應(yīng)客戶端請(qǐng)求時(shí),將提交的數(shù)據(jù)封裝成對(duì)象時(shí),使用了內(nèi)置的轉(zhuǎn)換器
SpringBoot 也支持自定義轉(zhuǎn)換器, 這個(gè)內(nèi)置轉(zhuǎn)換器在 debug 的時(shí)候, 可以看到, 提供了 124 個(gè)內(nèi)置轉(zhuǎn)換器. 看下源碼 GenericConverter-ConvertiblePair


自定義類型轉(zhuǎn)換器—應(yīng)用實(shí)例
1.需求說(shuō)明 : 演示自定義轉(zhuǎn)換器使用

2.代碼實(shí)現(xiàn)
1.修改src\main\resources\static\save.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>添加妖怪</title></head>
<body><h1>添加妖怪-坐騎[測(cè)試封裝 POJO;]</h1>
<form action="/savemonster" method="post">
編號(hào): <input name="id" value="100"><br/>
姓名: <input name="name" value="牛魔王"/><br/>
年齡: <input name="age" value="120"/> <br/>
婚否: <input name="isMarried" value="true"/> <br/>
生日: <input name="birth" value="2000/11/11"/> <br/>
<!-- 使用自定義轉(zhuǎn)換器關(guān)聯(lián)car, 字符串整體提交, 使用,號(hào)間隔 -->
坐騎:<input name="car" value="避水金晶獸,666.6"><br/>
<input type="submit" value="保存"/>
</form>
</body>
</html>2.修改src\main\java\com\llp\springboot\controller\ParameterController.java
@PostMapping("/savemonster")
public String saveMonster(Monster monster) {
//monster= Monster(id=100, name=牛魔王, age=120, isMarried=true, birth=Sat Nov 11 00:00:00 CST 2000, car=Car(name=避水金晶獸, price=666.6))
System.out.println("monster= " + monster);
return "success";
}3.自定義一個(gè)類型轉(zhuǎn)換器src\main\java\com\llp\springboot\config\WebConfig.java
/**
* 開啟lite模式,通過(guò)容器獲取bean時(shí)將是多例的
*/
@Configuration(proxyBeanMethods = false)
public class WebConfig {
@Bean
public WebMvcConfigurer webMvcConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addFormatters(FormatterRegistry registry) {
/**
* 1. 在addFormatters 方法中,增加一個(gè)自定義的轉(zhuǎn)換器
* 2. 增加自定義轉(zhuǎn)換器 String -> Car
* 3. 增加的自定義轉(zhuǎn)換器會(huì)注冊(cè)到 converters 容器中
* 4. converters 底層結(jié)構(gòu)是 ConcurrentHashMap 內(nèi)置有124轉(zhuǎn)換器
*/
registry.addConverter(new Converter<String, Car>() {
@Override
public Car convert(String content) {
if (!ObjectUtils.isEmpty(content)) {
//避水金晶獸,666.6
String[] split = content.split(",");
String name = split[0];
double price = Double.parseDouble(split[1]);
return new Car(name, price);
}
return null;
}
});
}
};
}
}
注意事項(xiàng)及使用細(xì)節(jié)
1.我們可以定義多個(gè)自定義轉(zhuǎn)換器
/**
* 開啟lite模式,通過(guò)容器獲取bean時(shí)將是多例的
*/
@Configuration(proxyBeanMethods = false)
public class WebConfig {
@Bean
public WebMvcConfigurer webMvcConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addFormatters(FormatterRegistry registry) {
Converter<String, Car> carConverter1 = new Converter<String, Car>() {
@Override
public Car convert(String content) {
if (!ObjectUtils.isEmpty(content)) {
//避水金晶獸,666.6
String[] split = content.split(",");
String name = split[0];
double price = Double.parseDouble(split[1]);
return new Car(name, price);
}
return null;
}
};
Converter<String, Monster> monsterConverter = new Converter<String, Monster>() {
@Override
public Monster convert(String s) {
return null;
}
};
Converter<String, Car> carConverter2 = new Converter<String, Car>() {
@Override
public Car convert(String s) {
System.out.println(s);
return null;
}
};
registry.addConverter(carConverter1);
//carConverter1、carConverter2的key均為 java.lang.String->com.llp.springboot.bean.Car組成
//因此carConverter2會(huì)覆蓋掉carConverter1
registry.addConverter(carConverter2);
registry.addConverter(monsterConverter);
}
};
}
}2.底層在定義了一變量名為convertes的ConCurrentHashMap用于存儲(chǔ)所有的類型轉(zhuǎn)換器,而key是由“原類型->目標(biāo)類型”構(gòu)成的,因此當(dāng)自定義的key相同時(shí)會(huì)覆蓋調(diào)之前的類型轉(zhuǎn)換器,這里我們定義了三個(gè)自定義轉(zhuǎn)換器但其中兩個(gè)時(shí)相同的key因此只會(huì)保留最后一次添加的類型轉(zhuǎn)換器

總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
webservlet注解無(wú)效訪問(wèn)servlet接口時(shí)報(bào)404解決辦法
這篇文章主要介紹了webservlet注解無(wú)效訪問(wèn)servlet接口時(shí)報(bào)404的解決辦法,如果在配置@WebServlet注解后出現(xiàn)404錯(cuò)誤,通常是由于URL映射不正確或Servlet類沒(méi)有正確加載,文中通過(guò)代碼介紹的非常詳細(xì),需要的朋友可以參考下2025-06-06
SpringBoot項(xiàng)目沒(méi)有把依賴的jar包一起打包的問(wèn)題解決
這篇文章主要介紹了SpringBoot項(xiàng)目沒(méi)有把依賴的jar包一起打包的問(wèn)題解決,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-09-09
SpringBoot整合MyBatis逆向工程及 MyBatis通用Mapper實(shí)例詳解
這篇文章主要介紹了SpringBoot整合MyBatis逆向工程及 MyBatis通用Mapper實(shí)例詳解 ,需要的朋友可以參考下2017-09-09
intellij idea如何配置網(wǎng)絡(luò)代理
intellij idea所在的這臺(tái)電腦本身上不了網(wǎng),要通過(guò)代理上網(wǎng),那么intellij idea怎么設(shè)置代理上網(wǎng)呢?今天通過(guò)本文給大家分享intellij idea如何配置網(wǎng)絡(luò)代理,感興趣的朋友一起看看吧2023-10-10
Springboot多環(huán)境開發(fā)及使用方法
這篇文章主要介紹了Springboot多環(huán)境開發(fā)及多環(huán)境設(shè)置使用、多環(huán)境分組管理的相關(guān)知識(shí),本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-03-03
SpringBoot中使用@Async注解失效場(chǎng)景及說(shuō)明
在Spring?Boot中,@Async注解就像一把刀,能幫你輕松處理那些耗時(shí)的任務(wù),讓主線程可以繼續(xù)忙別的事兒,不過(guò),跟所有強(qiáng)大的工具一樣,用不好它也可能出岔子,為了避免這些坑,咱們得深入了解下@Async注解,接下來(lái),咱們就來(lái)聊聊7種常見(jiàn)的@Async失效情況,需要的朋友可以參考下2024-07-07
Java8中常見(jiàn)函數(shù)式接口的使用示例詳解
在 Java 8 中,函數(shù)式接口是一個(gè)關(guān)鍵的特性,它們?cè)试S將方法作為參數(shù)傳遞或返回類型,本文為大家整理了一些常見(jiàn)的函數(shù)式接口的使用,希望對(duì)大家有所幫助2023-12-12
Springboot啟動(dòng)同時(shí)創(chuàng)建數(shù)據(jù)庫(kù)和表實(shí)現(xiàn)方法
這篇文章主要介紹了Springboot啟動(dòng)同時(shí)創(chuàng)建數(shù)據(jù)庫(kù)和表,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧2023-01-01
Eclipse 出現(xiàn)A configuration with this name already exists問(wèn)題解決方
這篇文章主要介紹了Eclipse 出現(xiàn)A configuration with this name already exists問(wèn)題解決方法的相關(guān)資料,需要的朋友可以參考下2016-11-11

