简体   繁体   中英

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

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

I have a project setup like:

项目结构

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

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!

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