63

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)

jb62
  • 2,224
  • 2
  • 14
  • 23

21 Answers21

111

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
jb62
  • 2,224
  • 2
  • 14
  • 23
27

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.
Kundan Atre
  • 3,853
  • 5
  • 26
  • 39
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
  • 4
    This answer appears to be correct. Users should be warned that the documentation (in [Section 76.3](https://docs.spring.io/spring-boot/docs/2.1.2.RELEASE/reference/htmlsingle/#howto-change-the-location-of-external-properties)) 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. – Adam Batkin Jan 20 '19 at 02:57
  • This is the correct answer, just helped me a lot. Thanks! – Yanick Nedderhoff Apr 27 '20 at 16:10
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>
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

Ayaz Alifov
  • 8,334
  • 4
  • 61
  • 56
8

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")
Dani
  • 4,001
  • 7
  • 36
  • 60
  • 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. – jb62 Oct 14 '15 at 16:52
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

Adarsh Singhal
  • 362
  • 1
  • 3
  • 12
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.

soundslikeodd
  • 1,078
  • 3
  • 19
  • 32
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.

G Butler
  • 139
  • 1
  • 3
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>

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.

Adir Dayan
  • 1,308
  • 13
  • 21
  • How should an updated `application.properties` look? – parsecer Mar 17 '23 at 23:33
  • @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 changes – Adir Dayan Mar 19 '23 at 13:00
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

Luan Kevin Ferreira
  • 1,184
  • 2
  • 16
  • 40
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.

cpd214
  • 605
  • 7
  • 11
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.

pawan
  • 51
  • 4
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)
Popeye
  • 253
  • 4
  • 13
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.

hooknc
  • 4,854
  • 5
  • 31
  • 60
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;
    }
}
Rajat
  • 2,467
  • 2
  • 29
  • 38
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.

Endran
  • 1,627
  • 1
  • 10
  • 15
  • 5
    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?](https://meta.stackexchange.com/questions/104227/is-it-acceptable-to-add-a-duplicate-answer-to-several-questions). – fcdt Aug 11 '20 at 12:13
  • I am new to answering on this platform i understand now how it works in duplicate questions and answers. Thank you! – AjayDarshanala Aug 12 '20 at 16:25
0

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

S V Naresh
  • 89
  • 1
  • 5
0

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

-1

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

Slok
  • 576
  • 1
  • 12
  • 27