当前位置: 首页> 科技> 互联网 > Springboot 集成 翻译功能

Springboot 集成 翻译功能

时间:2025/7/15 1:19:28来源:https://blog.csdn.net/qq_25987725/article/details/140761567 浏览次数:0次

项目中用到了翻译服务,我们来了解一下有提供翻译服务API。例如:Google Translate API, Microsoft Azure Translator Text API, AWS Translate。
这里我们使用Google Translate API

Google Translate API 是谷歌云平台的一部分,它提供了丰富的功能,包括文本翻译、语音翻译和自动检测语言等。通过简单的 RESTful API 调用,开发者可以在其应用中无缝集成翻译功能,支持超过100种语言的互译。

集成步骤:
1、在Google Cloud Console中创建一个项目。
2、启用Google Translate API。
3、创建服务账户或使用已有的账户,并获取相应的凭证。
4、在Spring Boot项目中pom.xml添加必要的依赖。

<dependencies><dependency><groupId>com.google.cloud</groupId><artifactId>google-cloud-translate</artifactId><version>1.4.0</version></dependency>
</dependencies>

5、配置凭证
在application.properties或application.yml中配置凭证文件路径:

# application.properties
google.application.credentials.location=/path/to/your/credentials-file.json

6、创建一个服务类来使用Google Translate API进行翻译:

import com.google.cloud.translate.Translate;
import com.google.cloud.translate.Translation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Locale;@Service
public class TranslationService {@Value("${google.application.credentials.location}")private String credentialsLocation;public String translate(String text, String targetLanguage) {try {Translate translate = TranslateOptions.newBuilder().setCredentials(ServiceAccountCredentials.fromStream(new FileInputStream(credentialsLocation))).build().getService();Translation translation = translate.translate(text, TranslateOption.targetLanguage(targetLanguage));return translation.getTranslatedText();} catch (IOException e) {e.printStackTrace();return "Error translating text";}}
}

7、创建控制器类

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.util.List;@RestController
public class TranslationController {private final TranslationService translationService;@Autowiredpublic TranslationController(TranslationService translationService) {this.translationService = translationService;}@GetMapping("/translate")public List<String> translateText(@RequestParam String text, @RequestParam String targetLanguage) throws IOException {List<Translation> translations = translationService.translate(text, targetLanguage);return translations.stream().map(Translation::getTranslatedText).toList();}
}
关键字:Springboot 集成 翻译功能

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: