Spring Boot app: Not picking up application.properties?
Asked Answered
M

21

66

I have a spring boot app I got here: https://github.com/christophstrobl/spring-data-solr-showcase/tree/4b3bbf945b182855003d5ba63a60990972a9de72

It compiles and works fine with: mvn spring-boot:run

However, when I click "run as Spring Boot app" in Spring Tools Suite, I get an error about not being able to find ${solr.host} which is set up in the application.properties file.

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'productServiceImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void org.springframework.data.solr.showcase.product.ProductServiceImpl.setProductRepository(org.springframework.data.solr.showcase.product.ProductRepository); nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'productRepository': Initialization of bean failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'solr.host' in string value "${solr.host}"

My applications.properties file looks like this:

# SPRING MVC
spring.view.suffix=.jsp
spring.view.prefix=/WEB-INF/views/

# SOLR
solr.host=http://192.168.56.11:8983/solr

The relevant class looks like this (the only place where the $solr.host variable is used). Also, if I directly address the SOLR server's IP (as in the commented code) the app starts fine.

* Copyright 2012 - 2014 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springframework.data.solr.showcase.config;

import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
import org.springframework.data.solr.core.SolrTemplate;
import org.springframework.data.solr.repository.config.EnableSolrRepositories;
import org.springframework.data.solr.server.SolrServerFactory;
import org.springframework.data.solr.server.support.MulticoreSolrServerFactory;

/**
 * @author Christoph Strobl
 */
@Configuration
@EnableSolrRepositories(basePackages = { "org.springframework.data.solr.showcase.product" })

public class SearchContext {

    @Bean
    public SolrServer solrServer(@Value("${solr.host}") String solrHost) {
        return new HttpSolrServer(solrHost);
    }

//  @Bean
//  public SolrServer solrServer(@Value("http://192.168.56.11:8983/solr") String solrHost) {
//      return new HttpSolrServer(solrHost);
//  }

    @Bean
    public SolrServerFactory solrServerFactory(SolrServer solrServer) {
        return new MulticoreSolrServerFactory(solrServer);
    }

    @Bean
    public SolrTemplate solrTemplate(SolrServerFactory solrServerFactory) {
        return new SolrTemplate(solrServerFactory);
    }

}

I'm including that "ProductRepository" -- the one mentioned in the error -- although there isn't much going on there...

* Copyright 2012 - 2014 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springframework.data.solr.showcase.product;

import java.util.Collection;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.solr.core.query.Query.Operator;
import org.springframework.data.solr.repository.Query;
import org.springframework.data.solr.repository.SolrCrudRepository;
import org.springframework.data.solr.showcase.product.model.Product;

/**
 * @author Christoph Strobl
 */
interface ProductRepository extends SolrCrudRepository<Product, String> {

    @Query(fields = { SearchableProductDefinition.ID_FIELD_NAME, SearchableProductDefinition.NAME_FIELD_NAME,
            SearchableProductDefinition.PRICE_FIELD_NAME, SearchableProductDefinition.FEATURES_FIELD_NAME,
            SearchableProductDefinition.AVAILABLE_FIELD_NAME }, defaultOperator = Operator.AND)
    Page<Product> findByNameIn(Collection<String> names, Pageable page);

}

I've got what seems like a "standard" file structure... code in src/main/java and so on. The application.properties file resides in src/main/resources.

Any suggestions gratefully accepted.

(Quick addition: This is running Tomcat as the embedded server)

Mongolism answered 8/10, 2015 at 17:58 Comment(0)
M
118

This was obscure - and the other answers were very helpful in getting me pointed in the right direction.

After trying the suggested solutions, I poked around deeper and found this in Project Properties --> Java Build Path --> Source(tab) --> Source folders on build path: [Exclusion section]

**/application.properties

Removing the exclusion fixed the issue and the values were picked up from the application.properties file during startup.

It may be worth noting that running this from the command line (in the directory with the .project file) bypassed the exclusion problem and worked fine.

mvn spring-boot:run
Mongolism answered 14/10, 2015 at 17:7 Comment(6)
Thank you! Saved my day. I had <directory>src/main/resources</directory> <filtering>false</filtering> in pom.xmlCreativity
<resources> <resource> <directory>src/main/resources</directory> <filtering>false or true works both - weird</filtering> <includes> <include>**.*</include> </includes> </resource> </resources>Creativity
Well, slap me silly... it worked. Note, though, that using mvn spring-boot:run did NOT get around the issue for me. FYI.Diderot
Thank you so much! But what in the Nine Hells made the exclusion appear in the first place!?Caspian
Had this weird behaviour for the first time ever when using Eclipse/STS and create ing a project using "New Spring Starter Project"Boff
Thank you so much, searched for 2h for this solution :/ <3Kuntz
D
29

For me it was due to packaging as pom

I had something in my pom.xml as below

<packaging>pom</packaging>

So if you have similar thing,

  1. Remove it for spring-boot App.

  2. Delete target folder or mvn clean.

  3. then mvn install.
  4. Watch your property under target/classes/application.properties file.
Dipper answered 1/2, 2019 at 6:58 Comment(4)
Is there a way to have POM packaging and still have the solution in a working state?Skeie
It seems, it is not: #27297808Skeie
thanks , this worked for me, but why this is causes the problem , can you explain ..!Ninebark
Packaging 'pom' is used for multimodule projects, since no jar is to be built for module. Other default packaging is 'jar'.Dissentious
T
25

I used Spring Boot 2.0.0 and I faced same problem. With version 1.4.3 it worked perfectly.

Reason is that if you define this argument:

-Dspring.config.location=file:/app/application-prod.yml

Spring Boot now is not adding default locations to search.

Solution:

-Dspring.config.location=file:/app/application-prod.yml,classpath:application.yml

See:

  1. /org/springframework/boot/context/config/ConfigFileApplicationListener.java
  2. https://docs.spring.io/spring-boot/docs/2.0.1.BUILD-SNAPSHOT/reference/htmlsingle/#appendix
Tommi answered 21/3, 2018 at 11:9 Comment(2)
This answer appears to be correct. Users should be warned that the documentation (in Section 76.3) states (after explaining how to override spring.config.location) "No matter what you set in the environment, Spring Boot always loads application.properties as described above." Another option would be to use spring.config.additional-location instead.Coniology
This is the correct answer, just helped me a lot. Thanks!Surgical
C
19

Include the following in your pom.xml. This should fix the issue.

<build>
    <resources>     
        <resource>
            <directory>src/main/resources</directory>
            <includes>                      
                <include>**/*.properties</include>                  
            </includes>
        </resource>            
    </resources>
</build>
Cloistral answered 17/7, 2018 at 11:34 Comment(1)
this worked for me, don't forget to mvn install after.Responsory
I
9

Declare the PropertySourcesPlaceholderConfigurer in your @Configuration class.

@Bean
public static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer() {

      return new PropertySourcesPlaceholderConfigurer();
}

And your property resource path with the proper annotation.

@PropertySource("classpath:your.properties")
Insurance answered 8/10, 2015 at 18:26 Comment(1)
Thanks Dani - this would clearly have worked if my situation had been straightforward. After trying this to no avail, I kept poking around and found that the directory containing application.configuration had been excluded explicitly in the Project Properties --> Java Build Path --> Source (tab) settings of the project I downloaded. As soon as I took out the exclusion, the application.properties got read in at startup as you would expect.Mongolism
C
9

Unfortunately, the mentioned approaches didn't help me. Adding Resources folder to Classpath solved the issue in my case.

Steps done:

  1. select you spring application and open Run configurations
  2. select Classpath tab
  3. select User Entries
  4. click on Advanced button
  5. select Add Folders and click OK button
  6. select your resources folder (/src/main/resources) and click OK button

enter image description here

Corrugation answered 28/12, 2021 at 19:1 Comment(0)
S
8

I resolved this by adding resources folder in build path.

Before

enter image description here

Do the following:-

  1. Click on Add folder...
  2. Add resources folder

enter image description here

Simoneaux answered 7/3, 2019 at 6:12 Comment(0)
M
1

I have some code for importing properties in Spring boot:

@SpringBootApplication
@EnableIntegration
@EnableScheduling
@ImportResource({ "classpath*:applicationContext.xml" })
@PropertySources(value = {
@PropertySource(ignoreResourceNotFound = true, value =     "classpath:properties/application.properties"),
@PropertySource(ignoreResourceNotFound = true, value = "classpath:properties/dbNhibernateConfig.properties"),
@PropertySource(ignoreResourceNotFound = true, value = "classpath:properties/mailConfiguration.properties"),
@PropertySource(ignoreResourceNotFound = true, value = "classpath:properties/errorcodes.properties") })
@IntegrationComponentScan("com.*.report.main")
public class AgilereportsApplication{

public static void main(String[] args) {
    SpringApplication.run(AgilereportsApplication.class, args);
}
}

When a spring boot application is created it reads application.properties from the resource folder by default. You don't need to import a property file.

Let say you create another property file with different name or you have moved the application.properties file to another folder. In my case I moved property file to resource\property folder so I am adding annotation @PropertySource to read these property files.

Monroy answered 12/1, 2017 at 3:45 Comment(2)
Please explain your answer.Dustproof
Hi added description.Monroy
S
1

I was having this problem. If I did a "Rebuild" from IntelliJ it would copy the application.properties from my src/test/reources folder to my target/test-classes and things would work. But, if I built from Maven, it would disappear from the target/test-classes folder and then the tests would fail when run by maven because it couldn't find the application.properties file. Low and behold, after much back and forth, I realized that my folder was named incorrectly (above is not a typo). I had "src/test/reources/application.properties" instead of "src/test/resources/application.properties". What a pain to spot that. The above answers helped me hone in on it and finally notice the typo. Was not as obvious as one might think. Watch out for that.

Sodium answered 19/8, 2019 at 22:11 Comment(0)
I
1

Your can always specify where you want spring to look for properties file like so in your pom.xml build section.

<resources>
    <resource>
        <directory>src/main/assembly</directory>
        <filtering>true</filtering>
    </resource>
    <resource>
        <directory>src/main/resources</directory>
        <filtering>true</filtering>
    </resource>
    <resource>
        <directory>src/main/config</directory>
        <filtering>true</filtering>
    </resource>

Instauration answered 1/5, 2020 at 11:14 Comment(0)
S
1

For me, every time I built just with IntelliJ build, and not with maven command. finally I found that application.properties that located in /target folder is not updated.

Only when I build using maven (even without clean), changes reflected to target folder.

Scutt answered 24/8, 2021 at 18:53 Comment(2)
How should an updated application.properties look?Arguable
@parsecer, I meant that I added some changes but they were missing in target folder, only after maven built the file in target folder updated with my changesScutt
T
1

I had the same kind of problem on IntelliJ, I could see the variables wired in the file, but it would not wire it when I launched my SpringBoot app.

I resolved the problem by deleting the .idea folder and invalidating cache + restart

Transatlantic answered 26/8, 2021 at 23:7 Comment(0)
S
1

Happened when I had to recreate my properties files after deleting them accidentally. Updating maven project worked for me

Stamp answered 24/2, 2022 at 16:56 Comment(0)
E
0

Adding PropertySourcesPlaceholderConfigurer and @PropertySource should work in case you want to keep your properties file name as applications.properties. However, AFAIK spring boot automatically picks up theapplication.properties file. So, you can also rename your applications.properties file to application.properties and it should work then.

Eichman answered 8/10, 2015 at 20:57 Comment(0)
C
0

I also faced the same problem it is not loading the application.properties file in class path. In my case the issue was that, if in your resource folder you have more than 1 resources i.e. properties file or xml files then you need to rename the resource folder to resources. Spring do it automatically for you but if its is not happening do it manually. It solved my issue, might help yours.

Clarisclarisa answered 30/11, 2016 at 11:54 Comment(0)
T
0

While creating the src/test/resources folder, tick the checkbox "Update exclusion filters in other source folders to solve nesting". And also use the PropertySource to load the src

@PropertySource(value = {"classpath:application-junit.properties"}, 
ignoreResourceNotFound = true)
Tureen answered 3/7, 2018 at 16:0 Comment(0)
G
0

In my case, the resource folder was not registered as a resource. I use IntelliJ, so I went to the module settings section, selected the resources folder and then clicked on resource on the upper part of the window. it started taking the application.properties file after that.

Gayelord answered 2/8, 2018 at 0:40 Comment(1)
I found this at File>Project Settings>Modules>select a module>Sources tab>Resources sub-tabHighboy
B
0

In my case, I had an Encryption Utility class and I was loading public and private keys from the base properties file.

adding @Component annotation worked for me.

@Component
public class AESEncryption {

private static String BASE64_ENCODED_PUBLIC_KEY;
private static String BASE64_ENCODED_PRIVATE_KEY;

    public AESEncryption(@Value("${BASE64_ENCODED_PUBLIC_KEY}") String BASE64_ENCODED_PUBLIC_KEY,
                         @Value("${BASE64_ENCODED_PRIVATE_KEY}") String BASE64_ENCODED_PRIVATE_KEY) {
        this.BASE64_ENCODED_PUBLIC_KEY = BASE64_ENCODED_PUBLIC_KEY;
        this.BASE64_ENCODED_PRIVATE_KEY = BASE64_ENCODED_PRIVATE_KEY;
    }
}
Buchenwald answered 18/4, 2020 at 6:31 Comment(0)
P
0

After spending hours and hours this worked!

Problem: Springboot 2.X.X ignores application.properties/application.yml and always start the tomcat on default port 8080.

Root cause: It is weird from Spring boot 2.x.x and seen in only some machines. Spring docs does not have a concept like this. This is a custom problem.

Solution: Provide spring.config.location as classpath:application.properties ( usually we use this practice for external config files but for this issue this works). Let me know if it also works for you.

Psi answered 11/8, 2020 at 11:47 Comment(2)
Before you paste this in even more locations, please take the time to read Is it acceptable to add a duplicate answer to several questions?.Landbert
I am new to answering on this platform i understand now how it works in duplicate questions and answers. Thank you!Psi
S
0

Try renaming the application properties file and try it. It should detect and compile. It worked for me.

Swampland answered 29/9, 2020 at 5:42 Comment(2)
Rename to what name?Silvan
If your prop file is application.properties, rename it to application1.properties. Define newly renamed filename in your class.Swampland
D
-1

In My case, it was logback-spring.xml. After removing spring in logback filename, it started working.

Duplet answered 25/2, 2021 at 4:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.