I am able to resolve my variables using @Value annotation but not via autowired Environment or WebApplicationContext.getEnvironment (which are both the same).
Spring version: 6.2.0
This is my web.xml snippet:
<servlet>
<servlet-name>app</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/app-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
Snippet to my app-context.xml
<context:property-placeholder location="WEB-INF/application.properties" />
My application.properties
config.path=settings/
Snippet of my Component code
@Autowired
private WebApplicationContext applicationContext;
@Autowired
Environment environment;
@Value("${config.path:conf/}")
private String configPath;
public test() {
log.info("configPath: {}", configPath); // this returns settings/
log.info("environment: {}", environment.getProperty("config.path")); // this returns null
log.info("environment: {}", applicationContext.getEnvironment.getProperty("config.path")); // this returns null too
}
**Comment From: mdeinum**
Which is as expected. The `context:property-placeholder` doesn't add a `PropertySource` to the `Environment`., instead if loads the properties creates its own representation and also uses the `Environment` as another source for properties and resolution. So it will only resolve with `@Value` not manually through the `Environment`.
See also [this answer](https://stackoverflow.com/a/21106326/2696260) on StackOverflow for more details.
**Comment From: kokhoor**
Thanks @mdeinum, I added code below to the afterPropertiesSet method of my WebMvcConfigurer, but notice that I need to have minimal autowiring in this file to ensure the code runs early before a lookup occurs:
var resource = new InputStreamResource(appContext.getServletContext()
.getResourceAsStream("WEB-INF/application.properties"));
var properties = new Properties();
PropertiesLoaderUtils.fillProperties(properties, resource);
((StandardServletEnvironment) appContext.getEnvironment()).getPropertySources().addLast(new PropertiesPropertySource("custom", properties));
```