[英]How to use text.properties in Spring Boot Service?
我有以下代码部分:
文本属性:
exception.NO_ITEM_FOUND.message=Item with email {0} not found
NoSuchElementFoundException:
public class NoSuchElementFoundException extends RuntimeException {
public NoSuchElementFoundException(String message) {
super(message);
}
}
服务:
public EmployeeDto findByEmail(String email) {
return employeeRepository.findByEmail(email)
.map(EmployeeDto::new)
.orElseThrow(() -> new NoSuchElementFoundException(NO_ITEM_FOUND));
}
此时,我不知道如何根据用户语言(目前只是默认语言)在 text.properties 上获取 NO_ITEM_FOUND 消息。
我创建了以下方法,但不确定是否需要它或应该如何使用它。
private final MessageSource messageSource;
private String getLocalMessage(String key, String... params){
return messageSource.getMessage(key,
params,
Locale.ENGLISH);
}
那么,如何正确地从服务中获取NO_ITEM_FOUND
文本属性?
您不需要getLocalMessage
方法。 只需将实例变量添加到您的服务类:
@Value("${exception.NO_ITEM_FOUND.message}")
private String NO_ITEM_FOUND;
并使用 @Value 进行注释,然后在代码的理想位置使用该变量:
@Service
public class EmployeeService {
@Value("${exception.NO_ITEM_FOUND.message}")
private String NO_ITEM_FOUND;
public EmployeeDto findByEmail(String email) {
return employeeRepository.findByEmail(email)
.map(EmployeeDto::new)
.orElseThrow(() -> new NoSuchElementFoundException(NO_ITEM_FOUND));
}
}
更新:
如果您在 Java 类中多次使用属性,而不是为每个属性定义单独的实例变量,您可以Autowire Environment类,然后在您的情况下像这样调用getProperty
方法:
import org.springframework.core.env.Environment;
@Service
public class EmployeeService {
private final Environment environment;
public EmployeeService(Environment environment) {
this.environment = environment;
}
public EmployeeDto findByEmail(String email) {
return employeeRepository.findByEmail(email)
.map(EmployeeDto::new)
.orElseThrow(() -> new NoSuchElementFoundException(environment.getProperty("exception.NO_ITEM_FOUND.message")));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.