Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

I am trying to use properties from a .properties file, but it doesn't seem to work. Here is my code:

@Service("ServiceFTP")
@Transactional
public class ServiceFTPImpl implements ServiceFTP {
    @Value("${project.ftp.adresse}")
    private String adresse;
    @Value("${project.ftp.login}")
    private String compte;
    @Value("${project.ftp.password}")
    private String motDePasse;
    @Value("${project.ftp.root}")
    private String ROOT;
    // [...]

This class uses @Value annotations to get the properties. It is also declared as a Spring Service and is linked to my infraContext.xml file :

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:context="http://www.springframework.org/schema/context"
   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
    <context:property-placeholder location="classpath:context-core.properties"/>
    <!-- [...]-->
</beans>

Using context:property-placeholder, I link this file to my context-core.properties file :

project.ftp.adresse = localhost
project.ftp.login = anonymous
project.ftp.password =
project.ftp.root = /anonymous/

This does make sense, right ?

But when I try to launch my project, Tomcat throw this exception:

ERROR [context.ContextLoader.initWebApplicationContext()] Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'ServiceFTP': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private java.lang.String project.sins.service.impl.ServiceFTPImpl.adresse; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'project.ftp.adresse' in string value "${project.ftp.adresse}"
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:287)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:607)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:925)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:472)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:388)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:293)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:111)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4887)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5381)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:633)
    at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:657)
    at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1636)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
    at java.util.concurrent.FutureTask.run(FutureTask.java:166)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:722)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private java.lang.String project.sins.service.impl.ServiceFTPImpl.adresse; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'project.ftp.adresse' in string value "${project.ftp.adresse}"
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:513)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:92)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:284)
    ... 27 more
Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'project.ftp.adresse' in string value "${project.ftp.adresse}"
    at org.springframework.util.PropertyPlaceholderHelper.parseStringValue(PropertyPlaceholderHelper.java:173)
    at org.springframework.util.PropertyPlaceholderHelper.replacePlaceholders(PropertyPlaceholderHelper.java:125)
    at org.springframework.core.env.AbstractPropertyResolver.doResolvePlaceholders(AbstractPropertyResolver.java:151)
    at org.springframework.core.env.AbstractPropertyResolver.resolveRequiredPlaceholders(AbstractPropertyResolver.java:142)
    at org.springframework.context.support.PropertySourcesPlaceholderConfigurer$2.resolveStringValue(PropertySourcesPlaceholderConfigurer.java:169)
    at org.springframework.beans.factory.support.AbstractBeanFactory.resolveEmbeddedValue(AbstractBeanFactory.java:748)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:740)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:730)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:485)
    ... 29 more

Or, in short:

java.lang.IllegalArgumentException: Could not resolve placeholder 'project.ftp.adresse' in string value "${project.ftp.adresse}"

Edit:

Here is my web.xml :

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         id="sins" version="2.5">
    <display-name>Project</display-name>
    <listener>
        <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
    </listener>
    <context-param>
        <param-name>log4jExposeWebAppRoot</param-name>
        <param-value>false</param-value>
    </context-param>
    <filter>
        <filter-name>ExpiresFilter</filter-name>
        <filter-class>org.apache.catalina.filters.ExpiresFilter</filter-class>
        <init-param>
            <param-name>ExpiresByType text/html</param-name>
            <param-value>now plus 0 seconds</param-value>
        </init-param>
        <init-param>
            <param-name>ExpiresByType application/json</param-name>
            <param-value>now plus 0 seconds</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>ExpiresFilter</filter-name>
        <url-pattern>/*</url-pattern>
        <dispatcher>REQUEST</dispatcher>
    </filter-mapping>
    <filter>
        <filter-name>EncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>EncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <filter>
        <filter-name>Spring OpenEntityManagerInViewFilter</filter-name>
        <filter-class>
            org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter
        </filter-class>
    </filter>
    <filter-mapping>
        <filter-name>Spring OpenEntityManagerInViewFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <listener>
        <listener-class>org.apache.struts2.tiles.StrutsTilesListener</listener-class>
    </listener>
    <context-param>
        <param-name>
            org.apache.tiles.impl.BasicTilesContainer.DEFINITIONS_CONFIG
        </param-name>
        <param-value>
            /WEB-INF/tiles/user.xml
        </param-value>
    </context-param>
    <resource-ref>
        <res-ref-name>jdbc/si_nsg</res-ref-name>
        <res-type>javax.sql.DataSource</res-type>
        <res-auth>Container</res-auth>
    </resource-ref>
    <session-config>
        <session-timeout>60</session-timeout>
    </session-config>
</web-app>

My infraContext.xml is imported in another .xml file named applicationContext.xml :

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:jee="http://www.springframework.org/schema/jee"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
    http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd">
    <bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
        <property name="environment">
            <bean class="org.springframework.web.context.support.StandardServletEnvironment"/>
        </property>
    </bean>
    <import resource="classpath:securityContext.xml"/>
    [...]
    <import resource="classpath:project/sins/persistenceContext.xml"/>
    <import resource="classpath:project/sins/infraContext.xml"/>
</beans>

I am obviously missing something, but I can't figure out what.

Please let me know if you need more details, as it is my first question here.

I'll try to answer as soon as I can.

Where is your infraContext.xml being loaded? Judging from the stacktrace it isn't included in the configuration loaded by the ContextLoaderListener. Please post your web.xml. – M. Deinum Nov 27, 2013 at 14:19 Problem is you have multiple instances of a PropertySourcesPlaceholderConfigurer one explicitly defined (why?) and one due to the namespace. The one in your applicationContext.xml isn't doing anything nor adding anything. Remove it. – M. Deinum Nov 27, 2013 at 14:33

In your configuration you have 2 PropertySourcesPlaceholderConfigurer instances.

applicationContext.xml

<bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
    <property name="environment">
        <bean class="org.springframework.web.context.support.StandardServletEnvironment"/>
    </property>
</bean>

infraContext.xml

<context:property-placeholder location="classpath:context-core.properties"/>

By default a PlaceholderConfigurer is going to fail-fast, so if a placeholder cannot be resolved it will throw an exception. The instance from the applicationContext.xml file has no properties and as such will fail on all placeholders.

Solution: Remove the one from applicationContext.xml as it doesn't add anything it only breaks things.

Awesome, thank you, so I take it that in Spring that there can only be one instance of a PlaceholderConfigurer ? – Mushtaq Jameel Mar 6, 2015 at 9:15 No you can have multiple however by default they fail fast if a placeholder isn't found. You can disable this by setting ignore-unresolved-placeholders to true. – M. Deinum Mar 6, 2015 at 10:22

I got same error in my Micro-service, whenever you declare @Value annotation in program i.e @Value("${project.api.key}")

make sure that your application.properties file with same values should not be blank project.api.key= add some values

MostIMP :otherwise it will throw error "Error creating bean with name 'ServiceFTP': Injection of autowired dependencies"

Thanks, this solved my issue. I'm curious though, why/how is the maven resources plugin affecting the spring placeholders... I never would have guessed they were related! – BitfulByte Jul 1, 2020 at 12:16 I had an extra line under <filtering> ... <excludes> which was causing the issue in my case, though nothing was being excluded. – emarshah Apr 13, 2021 at 0:52

This Issue occurs if the application is unable to access the some_file_name.properties file.Make sure that the properties file is placed under resources folder in spring.

Trouble shooting Steps

1: Add the properties file under the resource folder.

2: If you don't have a resource folder. Create one by navigating new by Right click on the project new > Source Folder, name it as resource and place your properties file under it.

For annotation based Implementation

Add @PropertySource(ignoreResourceNotFound = true, value = "classpath:some_file_name.properties")//Add it before using the place holder

Example:

Assignment1Controller.Java

@PropertySource(ignoreResourceNotFound = true, value = "classpath:assignment1.properties")
@RestController  
public class Assignment1Controller {
//  @Autowired
//  Assignment1Services assignment1Services;
    @Value("${app.title}")
    private String appTitle;
     @RequestMapping(value = "/hello")  
        public String getValues() {
          return appTitle;

assignment1.properties

app.title=Learning Spring
                In my case application.yaml (can be application.properties) under test/resources shadowed the same file under main/resources - so my tests failed due to a missing variable in the former file.
– Denis Abakumov
                Jul 12, 2022 at 16:55

You can also try default values. spring-value-annotation

Default values can be provided for properties that might not be defined. In this example the value “some default” will be injected:

@Value("${unknown.param:some default}")
private String someDefault;

If the same property is defined as a system property and in the properties file, then the system property would be applied.

Okay...this helped me. In fact my app has many application-<profile>.yml files, and I was receiving an error due to a new property defined in the main config. file only. Honestly I was expecting to define the value only once in the main configuration, and in case override the value in a profile-specific configuration. Looks like it doesn't work like that, and a default value must be always provided. Now I understand why my java configurations were failing, when I didn't initialize properties with a default value! Can be this behaviour changed? Thanks :-) – funder7 Oct 22, 2020 at 21:56

In my case, I was careless while merging the application.yml file, and I've unnecessary indented my properties to the right.

I've indented it like this:

spring:
    application:
       name: applicationName
............................
    myProperties:
       property1: property1value

While the code expected it to be like this:

spring:
    application:
        name: applicationName
.............................
myProperties:
    property1: property1value

In my case I had the same issue on running from eclipse. Just did the following to resolve it: Right Click the Project --> Mavan --> Update Project.

And it worked!

This worked for me. I had no ident errors, but my program was giving an error which was solved after updating the project. – Enchantres Apr 29, 2022 at 20:23 <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <addResources>true</addResources> </configuration> </plugin> </plugins> </build>

Example in class Java

@Configuration
@Slf4j
public class MyAppConfig {
    @Value("${foo}")
    private String foo;
    @Value("${bar}")
    private String bar;
    @Bean("foo")
    public String foo() {
        log.info("foo={}", foo);
        return foo;
    @Bean("bar")
    public String bar() {
        log.info("bar={}", bar);
        return bar;
    [ ... ]

In the properties files :

src/main/resources/application.properties

foo=all-env-foo

src/main/resources/application-rec.properties

bar=rec-bar

src/main/resources/application-prod.properties

bar=prod-bar

In the VM arguments of Application.java

-Dspring.profiles.active=[rec|prod]

Don't forget to run mvn command after modifying the properties !

mvn clean package -Dmaven.test.skip=true

In the log file for -Dspring.profiles.active=rec :

The following profiles are active: rec
foo=all-env-foo
bar=rec-bar

In the log file for -Dspring.profiles.active=prod :

The following profiles are active: prod
foo=all-env-foo
bar=prod-bar

In the log file for -Dspring.profiles.active=local :

Could not resolve placeholder 'bar' in value "${bar}"

Oups, I forget to create application-local.properties.

This error appears because the spring project doesn't read the file properties (bootstrap.yml or application.yml). In order to resolve this, you must add dependency in your pom.xml

   <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-context</artifactId>
    </dependency>

I´m frequently running into this issue on some custom properties that could not be found using IntelliJ IDEA - likely after changing branches.

What helpes in my case is

File -> Invalidate Caches / Restart

I had the assumption that it is more likely a Gradle caching issue than an IDE issue, but ./gradle clean did not help

I fell for this fix at first but now I see it's nothing but a dirty workaround, and here's why. You can achieve the same effect by replacing the variable with a random string like this: @Value("$@#$%^&*()"). This will simply break your variable - so you don't get the error. As @Thisisalexis said under Ben G's response, "that's because the application is not looking for the property in any given properties file anymore, since you are not using the right syntax." So don't get deceived by the simplicity of this "fix" - it fixes nothihng. – Denis Abakumov Jul 12, 2022 at 16:47

I run into this when I created an @Configuration class with a prefix e.g. foo.bar then went ahead to attempt to autowire a property in another class using @Value("${foo.bay.xyz}").

The solution was to add the xyz property to the configuration class and access it from an autowired bean of that class.

I could not find the reason for this in the docs but my guess is that spring was binding all properties under the foo.bar prefix under the configuration class.

When you're using Spring Boot with spring-boot-starters and you redefine variables in .yml / .properties file, make sure you using custom names for variables. For example you're using spring-boot-starter-mail. And defining variables from mail-starter in the .yml file next way:

spring:
  mail:
    host: ${my_smtp_host}

In this case you'll get an IllegalArgumentException: Could not resolve placeholder 'my_smtp_host' in string value "${my_smtp_host}"

To solve this issue just make custom variable. For example:

my-mail:
  host: ${my_smtp_host}

Another note - if you're using Openshift make sure your variable my_smtp_host not starting from digit: change this -> ${123_my_smtp_host} to this -> ${my_smtp_host}

I don't think that's a proper solution; of course it prevent the application to fail, but that's because the application is not looking for the property in any given properties file anymore, since you are not using the right syntax. – Thisisalexis May 16, 2022 at 17:49

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.