2

I'm trying to read a configuration files which I put under /WEB-INF/config folder. The reason is that the Jetty Maven plugin does not support resource filtering. Can some one please explain me how to do that using Spring Java configuration feature ?

I know that <context: property-placeholder ... /> should work, but i dont want to use XML.

application dirs

├───META-INF
└───WEB-INF
    ├───classes
    ├───config
    ├───i18n
    ├───lib
    ├───pages
    └───resources

property sources configuration

@Configuration
@EnableWebMvc
@PropertySources({
    @PropertySource("log4j.properties"),
    @PropertySource("general.properties") }
)
public class ApplicationContext extends WebMvcConfigurerAdapter {

    @Autowired
    ServletContext servletContext;

    @Bean
    public PropertyPlaceholderConfigurer properties() {
        PropertyPlaceholderConfigurer propertySources = new PropertyPlaceholderConfigurer();
        Resource[] resources = new ServletContextResource[] {
                        new ServletContextResource(servletContext, "WEB-INF/config/log4j.properties"),
                        new ServletContextResource(servletContext, "WEB-INF/config/general.properties")
        };
        propertySources.setLocations(resources);
        propertySources.setIgnoreUnresolvablePlaceholders(true);
        return propertySources;
    }
}

exception:

java.lang.IllegalArgumentException: Cannot resolve ServletContextResource without ServletContext
Community
  • 1
  • 1
Greg
  • 21
  • 1
  • 2

2 Answers2

2

As @M.Deinum said, there is no need to configure PropertyPlaceholderConfigurer manually: Spring Boot has PropertyPlaceholderAutoConfiguration to get deal with that.

Everything what you need is @PropertySource.

Since your general.properties is located in the ServletContext it should be like this:

@PropertySource("/WEB-INF/config/general.properties")

Note, it does not make sence to do the same for log4j.properties. Consider to move it to the /WEB-INF/classes to allow for log4j to pick up it automatically.

Artem Bilan
  • 113,505
  • 11
  • 91
  • 118
-1

Use following lines of code with @Autowired Annotation.

@Autowired
ServletContext servletContext;
String filePath = servletContext.getRealPath("/WEB-INF/XXXX/");
File file = new File(filePath );
FileInputStream fileInput = new FileInputStream(file);
itsmysterybox
  • 2,748
  • 3
  • 21
  • 26
Shiva
  • 1
  • 1