I have the following code parts:
text.properties:
exception.NO_ITEM_FOUND.message=Item with email {0} not found
NoSuchElementFoundException:
public class NoSuchElementFoundException extends RuntimeException {
public NoSuchElementFoundException(String message) {
super(message);
}
}
service:
public EmployeeDto findByEmail(String email) {
return employeeRepository.findByEmail(email)
.map(EmployeeDto::new)
.orElseThrow(() -> new NoSuchElementFoundException(NO_ITEM_FOUND));
}
At this point, I have no idea how to get the NO_ITEM_FOUND message on text.properties based on the user language (for now just default one).
I created the following method, but not sure if I need it or how should I use it.
private final MessageSource messageSource;
private String getLocalMessage(String key, String... params){
return messageSource.getMessage(key,
params,
Locale.ENGLISH);
}
So, how can I get NO_ITEM_FOUND
text property from service properly?
CodePudding user response:
You do not need getLocalMessage
method. Just add an instance variable to your service class:
@Value("${exception.NO_ITEM_FOUND.message}")
private String NO_ITEM_FOUND;
And annotated with @Value and then use the variable in desirable place of your code:
@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));
}
}