Search code examples
javaspring-bootexceptionmultilingual

How to use text.properties in Spring Boot Service?


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?


Solution

  • 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));
        }
    
    }
    

    UPDATE:

    If you have multiple usage of a properties in a Java class, instead of defining separate instance variable for each property, you can Autowire Environment class and then call getProperty method just like this in your case:

    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")));
        }
    
    }