简体   繁体   中英

What is best way to externalize error messages(resource bundles) out of src code in spring and springboot?

I am looking for best way to externalize my validation error messages out of my src code in spring and spring boot application, in order to avoid build/deployment on each time the error messages changes. Is there possibly any such ways to achieve it?

You can maintain all the validation error or success messages in a properties file. If you want to externalize, you can place the properties file outside the spring boot jar file. It is not necessary to put the configuration inside jar. I provide below the code snippet to achieve it.

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;

    @Configuration
    @PropertySources({
      @PropertySource("file:config/other-config.properties"),
      @PropertySource("file:config/app-config.properties")
    })
    public class ExternalConfig {

      @Bean
      public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
        return new PropertySourcesPlaceholderConfigurer();
      }
    }

In the above code, in the line @PropertySource("file:config/app-config.properties") , config is the name of the folder or directory which contains many properties files like "app-config.properties". For better understanding, I provide below the image, external config file and spring boot jar will look like this finally.

在此输入图像描述

The default resource bundle framework assumes your resource bundles are property files in your resources folder. So they are packaged inside your jar file as part of your build process.

However you can implement your own ResourceBundle loading:

https://docs.oracle.com/javase/tutorial/i18n/resbundle/control.html

You can then opt to use other mechanisms, including using a database instead of property files (with a TTL to cache messages for a specific period of time). This way you don't even have to restart the application when a message changes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM