Reputation: 1038
I am trying to inject values of a properties file into a controller in a spring mvc project. I am using spring version 5.0.4. Below is the definition of my servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd">
<!-- Step 3: Add support for component scanning -->
<context:component-scan base-package="mu.mra" />
<!-- Step 4: Add support for conversion, formatting and validation support -->
<mvc:annotation-driven/>
<!-- Step 5: Define Spring MVC view resolver -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
<util:properties id="countryOptions" location="classpath: countries.properties" />
</beans>
the properties file is located in the src/main/resources folder. But unfortunately I am getting the error below
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'studentController': Unsatisfied dependency expressed through field 'countryOptions'; nested exception is org.springframework.beans.factory.BeanExpressionException: Expression parsing failed; nested exception is org.springframework.expression.spel.SpelEvaluationException: EL1021E: A problem occurred whilst attempting to access the property 'countryOptions': 'Error creating bean with name 'countryOptions': Invocation of init method failed; nested exception is java.io.FileNotFoundException: class path resource [ countries.properties] cannot be opened because it does not exist'
I am not too sure about the location of the properties file. Should it be in the WEB-INF folder? I would like some explanation as well on this if possible.
Thanks, Ashley
Upvotes: 1
Views: 1386
Reputation: 553
You are right, the properties files do exist in the src/main/resources you can access them as following
<util:properties id="countryOptions" location="classpath:countries.properties" />
Or using the annotations
@Value( "${property.needed}" )
private String property;
Upvotes: 1