How to load `messages.properties` in java packages (Spring Boot)?

4.8k views Asked by At

I want to load multiple messages.properties files from the java packages.

I have a project setup like:

Project structure

And AppConfig.java is:

@Configuration
public class AppConfig extends AcceptHeaderLocaleResolver implements WebMvcConfigurer {
    ...
    @Bean
    public ResourceBundleMessageSource messageSource() {
        final ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();

        messageSource.setBasenames(
            "file:./project/foo/messages.properties", // Not working
            "file:./project/bar/messages.properties"
        );

        messageSource.setDefaultEncoding("UTF-8");
        
        return messageSource;
    }
}

But the above setup is not working. How do I load multiple messages.properties from the java source package? Is it even possible?

I just don't want to use the folder src/main/resources - I want to put the file messages.properties in each package folder.

Also, I'd like to rename the file like ProjectFooMessage.properties to match the filename (custom name). Please enlighten me!

Note: I am using Spring Boot 2.1.14

1

There are 1 answers

5
young-ceo On BEST ANSWER

I finally figured it out. I need to change pom.xml

// pom.xml
...
<resources>
  <resource>
    <directory>src/main/resources</directory>
  </resource>
  <resource>
    <directory>src/main/java</directory>
      <includes>
        <include>**/*.properties</include>
      </includes>
  </resource>
</resources>
...

The key part is <include>**/*.properties</include> - so that I can include all *.properties files in the Java source folders.

Then, I can access the file with the below code:

...
messageSource.setBasename("classpath:project/foo/messages");
...

WOOHOO!