web-dev-qa-db-fra.com

Application Spring Boot: vous ne récupérez pas application.properties?

J'ai une application de démarrage de printemps que j'ai ici: https://github.com/christophstrobl/spring-data-solr-showcase/tree/4b3bbf945b182855003d5ba63a60990972a9de72

Il compile et fonctionne bien avec: mvn spring-boot:run

Cependant, lorsque je clique sur «Exécuter en tant qu'application Spring Boot» dans Spring Tools Suite, un message d'erreur indiquant que ${solr.Host} est configuré dans le fichier application.properties apparaît.

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}"

Mon fichier applications.properties ressemble à ceci:

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

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

La classe pertinente ressemble à ceci (le seul endroit où la variable $ solr.Host est utilisée). En outre, si je m'adresse directement à l'adresse IP du serveur SOLR (comme dans le code commenté), l'application démarre correctement. 

* 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);
    }

}

J'inclus ce "ProductRepository" - celui mentionné dans l'erreur - bien qu'il n'y ait pas grand chose là-bas ...

* 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);

}

J'ai ce qui semble être une structure de fichier "standard" ... code dans src/main/Java et ainsi de suite. Le fichier application.properties réside dans src/main/resources.

Toute suggestion acceptée avec reconnaissance.

(Ajout rapide: ceci exécute Tomcat en tant que serveur intégré)

9
jb62

C'était obscur - et les autres réponses m'ont beaucoup aidé à me faire pointer dans la bonne direction.

Après avoir essayé les solutions suggérées, j'ai approfondi et trouvé ceci dans les propriétés du projet -> Chemin de construction Java -> Source (onglet) -> Dossiers sources sur le chemin de construction:

**/application.properties

La suppression de l'exclusion a résolu le problème et les valeurs ont été extraites du fichier application.properties au démarrage.

Il peut être intéressant de noter que son exécution à partir de la ligne de commande (dans le répertoire contenant le fichier .project) a contourné le problème d'exclusion et a fonctionné correctement.

mvn spring-boot:run
36
jb62

J'ai utilisé Spring Boot _ {2.0.0 et j'ai rencontré le même problème… .. Avec la version 1.4.3, il a parfaitement fonctionné.

Reason est que si vous définissez cet argument:

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

Spring Boot n'est pas en train d'ajouter des emplacements par défaut à la recherche.

Solution:

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

Voir: 

  1. /org/springframework/boot/context/config/ConfigFileApplicationListener.Java
  2. https://docs.spring.io/spring-boot/docs/2.0.1.BUILD-SNAPSHOT/reference/htmlsingle/#appendix
6
Vova Perebykivskyi

Déclarez le PropertySourcesPlaceholderConfigurer dans votre classe @Configuration.

@Bean
public static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer() {

      return new PropertySourcesPlaceholderConfigurer();
}

Et votre chemin de ressource de propriété avec l'annotation proprement dite.

@PropertySource("classpath:your.properties")
2
Dani

Incluez les éléments suivants dans votre pom.xml .Cela devrait résoudre le problème.

<build>
    <resources>     
        <resource>
            <directory>src/main/resources</directory>
            <includes>                      
                <include>**/*.properties</include>                  
            </includes>
        </resource>            
    </resources>
</build>
1
Captain.Karthick

J'ai du code pour importer des propriétés dans 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);
}
}

Lorsqu'une application de démarrage printanier est créée, elle lit application.properties par défaut dans le dossier de ressources. Vous n'avez pas besoin d'importer un fichier de propriétés. 

Supposons que vous créiez un autre fichier de propriété avec un nom différent ou que vous ayez déplacé le fichier application.properties dans un autre dossier. Dans mon cas, j'ai déplacé le fichier de propriétés dans le répertoire resource\property , de sorte que j'ajoute l'annotation @PropertySource pour lire ces fichiers de propriétés.

1
user3396256

Pour moi, cela était dû à un emballage en tant que pom  

J'ai eu quelque chose dans mon pom.xml comme ci-dessous 

<packaging>pom</packaging>

Donc, si vous avez la même chose,

  1. Retirez-le pour l'application Spring-Boot.

  2. Supprimer le dossier cible ou mvn clean. 

  3. puis mvn installer.
  4. Regardez votre propriété dans le fichier target/classes/application.properties.
1
Kundan Atre

L'ajout de PropertySourcesPlaceholderConfigurer et @PropertySource devrait fonctionner si vous souhaitez conserver le nom du fichier de propriétés sous applications.properties. Cependant, AFAIK spring boot récupère automatiquement le fichierapplication.properties. Ainsi, vous pouvez également renommer votre fichier applications.properties en application.properties et il devrait alors fonctionner.

0
cpd214

Lors de la création du dossier src/test/resources, cochez la case "Mettre à jour les filtres d'exclusion dans d'autres dossiers sources pour résoudre les problèmes d'imbrication". Et aussi utiliser le PropertySource pour charger le src

@PropertySource(value = {"classpath:application-junit.properties"}, 
ignoreResourceNotFound = true)
0
Popeye

Dans mon cas, la ressource foulder n'a pas été enregistrée en tant que ressource. J'utilise IntelliJ, alors je suis allé dans la section des paramètres du module, j'ai sélectionné le dossier des ressources, puis cliqué sur ressource dans la partie supérieure de la fenêtre. il a commencé à prendre le fichier application.properties après cela

0
Levant Alejandro

J'ai également rencontré le même problème, il ne charge pas le fichier application.properties dans le chemin d'accès aux classes. Dans mon cas, le problème était que, si dans votre dossier de ressources, vous avez plus de 1 ressources, à savoir un fichier de propriétés ou des fichiers xml, vous devez renommer le dossier resource en resources . Spring le fait automatiquement pour vous, mais si cela ne se produit pas, faites-le manuellement. Il a résolu mon problème, pourrait aider le vôtre.

0
pawan