Tengo una aplicación de arranque de primavera que tengo aquí:
https://github.com/christophstrobl/spring-data-solr-showcase/tree/4b3bbf945b182855003d5ba63a60990972a9de72
Compila y funciona bien con: mvn spring-boot:run
Sin embargo, cuando hago clic en “ejecutar como aplicación Spring Boot” en Spring Tools Suite, aparece un error que indica que no puedo encontrar ${solr.host}
que se configura en el archivo application.properties.
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}"
Mi archivo application.properties se ve así:
# SPRING MVC
spring.view.suffix=.jsp
spring.view.prefix=/WEB-INF/views/
# SOLR
solr.host=http://192.168.56.11:8983/solr
La clase relevante se ve así (el único lugar donde se usa la variable $solr.host). Además, si me dirijo directamente a la IP del servidor SOLR (como en el código comentado), la aplicación comienza bien.
* 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);
}
}
Incluyo ese “ProductRepository”, el mencionado en el error, aunque no hay mucho que hacer allí…
* 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);
}
Tengo lo que parece una estructura de archivo “estándar”… código en src/main/java y así sucesivamente. El archivo application.properties reside en src/main/resources.
Cualquier sugerencia se acepta con gratitud.
(Agregado rápido: esto está ejecutando Tomcat como servidor integrado)
Esto fue oscuro, y las otras respuestas fueron muy útiles para orientarme en la dirección correcta.
Después de probar las soluciones sugeridas, investigué más a fondo y encontré esto en Propiedades del proyecto –> Ruta de compilación de Java –> Fuente (pestaña) –> Carpetas de origen en la ruta de compilación: [Exclusion section]
**/application.properties
La eliminación de la exclusión solucionó el problema y los valores se recogieron del archivo application.properties durante el inicio.
Puede valer la pena señalar que ejecutar esto desde la línea de comando (en el directorio con el archivo .project) evitó el problema de exclusión y funcionó bien.
mvn spring-boot:run
-
Gracias por hacer un seguimiento de esto. Tuve el mismo problema y estaba buscando en el lugar equivocado.
– Punit Raizada
29 de agosto de 2016 a las 16:53
-
Muy buen hallazgo. Muchas gracias
– Pulkit Gupta
7 de julio de 2017 a las 9:15
-
Yo tuve el mismo problema. Estaba ejecutando Eclipse Neon en Windows 8 y Eclipse Oxygen en Linux. Mismo proyecto (mismo espacio de trabajo) utilizado para trabajar en Windows y no en Linux. La eliminación de la exclusión en el proyecto Linux ayudó.
– Visrahane
8 de julio de 2017 a las 21:07
-
¡Gracias! salvó mi día Tenía
src/main/resources false en pom.xml– Alex
11/10/2017 a las 19:22
-
src/main/resources false or true funciona tanto – raro **.* – Alex
11/10/2017 a las 19:32
Para mí fue debido al embalaje como pompón
Tenía algo en mi pom.xml como se muestra a continuación
<packaging>pom</packaging>
Entonces, si tienes algo similar,
-
Quítelo para la aplicación spring-boot.
-
Eliminar carpeta de destino o mvn clean.
- luego instalar mvn.
- Mire su propiedad en el archivo target/classes/application.properties.
-
¿Hay alguna manera de tener un empaque POM y aún tener la solución en un estado de funcionamiento?
– Darek
16 de diciembre de 2019 a las 16:11
-
Parece que no lo es: stackoverflow.com/questions/27297308/…
– Darek
16 dic 2019 a las 16:15
-
gracias, esto funcionó para mí, pero por qué esto causa el problema, ¿puedes explicarlo?
– Tayab Hussein
10 de enero de 2020 a las 20:05
Vova Perebykivskyi
solía Bota de primavera 2.0.0 y me enfrenté al mismo problema. Con versión 1.4.3 funcionó perfectamente.
Razón es que si defines este argumento:
-Dspring.config.location=file:/app/application-prod.yml
Bota de primavera ahora no está agregando ubicaciones predeterminadas para buscar.
Solución:
-Dspring.config.location=file:/app/application-prod.yml,classpath:application.yml
Ver:
- /org/springframework/boot/context/config/ConfigFileApplicationListener.java
- https://docs.spring.io/spring-boot/docs/2.0.1.BUILD-SNAPSHOT/reference/htmlsingle/#appendix
-
Esta respuesta parece ser correcta. Se debe advertir a los usuarios que la documentación (en Sección 76.3) estados (después de explicar cómo anular
spring.config.location
) “No importa lo que establezca en el entorno, Spring Boot siempre carga application.properties como se describe anteriormente”. Otra opción sería usarspring.config.additional-location
en cambio.–Adam Batkin
20 de enero de 2019 a las 2:57
-
Esta es la respuesta correcta, me ayudó mucho. ¡Gracias!
– Yanick Nedderhof
27 de abril de 2020 a las 16:10
Incluya lo siguiente en su pom.xml. Esto debería solucionar el problema.
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
</includes>
</resource>
</resources>
</build>
Desafortunadamente, los enfoques mencionados no me ayudaron. Agregar carpeta de recursos a ruta de clases resolvió el problema en mi caso.
Pasos realizados:
- seleccione su aplicación de primavera y abra Ejecutar configuraciones
- seleccionar ruta de clases pestaña
- seleccionar Entradas de usuario
- haga clic en Avanzado botón
- seleccione Agregar carpetas y haga clic en el botón Aceptar
- selecciona tu recursos carpeta (/src/main/resources) y haga clic en el botón Aceptar
Adarsh Singhal
Resolví esto agregando la carpeta de recursos en la ruta de compilación.
Antes
Haz lo siguiente:-
- Haga clic en Agregar carpeta…
- Agregar carpeta de recursos
Declare PropertySourcesPlaceholderConfigurer en su clase @Configuration.
@Bean
public static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
Y la ruta de recursos de su propiedad con la anotación adecuada.
@PropertySource("classpath:your.properties")
-
Gracias Dani, esto claramente habría funcionado si mi situación hubiera sido sencilla. Después de probar esto sin éxito, seguí hurgando y descubrí que el directorio que contenía application.configuration se había excluido explícitamente en las Propiedades del proyecto –> Java Build Path –> Configuración de fuente (pestaña) del proyecto que descargué. Tan pronto como eliminé la exclusión, application.properties se leyó al inicio como era de esperar.
– jb62
14/10/2015 a las 16:52