Am facing this error before starting the application? - spring-boot

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2018-04-12 18:47:51.811 ERROR 340 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
APPLICATION FAILED TO START
Description:
Field leadRepository in com.example.lead.controller.LeadController required a bean of type 'com.example.lead.repo.LeadRepository' that could not be found.
Action:
Consider defining a bean of type 'com.example.lead.repo.LeadRepository' in your configuration.

package com.example.lead.repo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
// import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.example.leadmodel.Lead;
import com.example.leadmodel.LeadEntity;
#Repository
public interface LeadRepository extends JpaRepository<Lead, Integer> {
#Bean
#Autowired
Lead findOne(Integer lead_id);
void save(LeadEntity leadEntity);
}

Related

Component Scan with both including package and excluding a class is not working SpringBoot

I am trying to scan a package com.training and want to exclude a specific class(SDIAuthorizerConfig.java) from scanning in componenet scan but it doesnt seems like working
package com.training.execution.tom.action;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import com.training.foundation.core.application.SDIServiceApplication;
import com.training.foundation.core.authorizer.config.SDIAuthorizerConfig;
import org.springframework.context.annotation.FilterType;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
#SpringBootApplication
#ComponentScan(basePackages = "com.training",excludeFilters = #Filter(type= FilterType.ASSIGNABLE_TYPE, value=SDIAuthorizerConfig.class))
#EnableGlobalMethodSecurity(securedEnabled = true)
#EnableEurekaClient
#EnableAutoConfiguration
public class TOMActionServiceApplication extends SDIServiceApplication{
public static void main(String[] args) {
SpringApplication.run(TOMActionServiceApplication.class, args);
}
}
And getting this below error while starting the application in tomcat
Error starting Tomcat context. Exception: org.springframework.beans.factory.UnsatisfiedDependencyException. Message: Error creating bean with name 'SDIAuthorizerFilter': Unsatisfied dependency expressed through field 'authorizer'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'SDILDAPAuthorizer': Unsatisfied dependency expressed through field 'populator';
nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'SDIAuthorizerConfig': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'sdi.ldap.url' in value "${sdi.ldap.url}"
the above property is being referenced inside SDIAuthorizerConfig class which I don't want my component scan to include so I have used the below but it still being scanned.
#ComponentScan(basePackages = "com.training",excludeFilters = #Filter(type= FilterType.ASSIGNABLE_TYPE, value=SDIAuthorizerConfig.class))

org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'environment' available

I am getting this following exception on my production while running my code. I don't know what I am making mistake, the same code is happily running on my local machine, please help
Feb 19 13:46:40 ip-10-0-77-139 server: ShopifyGetItems: Service
function shop.getShopifyDomain():
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'hibernateConfig': Injection of autowired
dependencies failed; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
bean named 'environment' available
import java.util.Properties;
import javax.sql.DataSource;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#Configuration
#EnableTransactionManagement
#ComponentScan({ "com.webbee.app" })
#PropertySource(value = { "classpath:internal.properties" })
public class HibernateConfig {
#Autowired
private Environment environment;
private Properties hibernateProperties() {
System.out.println(environment.getRequiredProperty("hibernate.dialect"));
Properties properties = new Properties();
properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));
properties.put("hibernate.hbm2ddl.auto", environment.getRequiredProperty("hibernate.hbm2ddl.auto"));
properties.put("hibernate.jdbc.batch_size", 1000); // batch size for save or update
return properties;
}
}
It will be good, if you can debug the issue -
System.out.println("Created beans: " + Arrays.toString(context.getBeanNamesForType(Environment.class)));
if you are getting empty list it means, your bean is not instantiated in spring container and there is some problem with component scan.
This helped me in spring boot 2.4 but not in 2.6
spring:
config:
use-legacy-processing: false

Spring boot Multi-module project multi-datasource

I'm trying to develop a multi-module spring boot project with multi-datasource connection. I have separate this project in 5 modules:
-springboot-multiple-maven-modules:
1. domain -> database2's model
2. domain2 -> database2's model
3. persistence -> database1's persistence
4. persistence2 -> database2's persistence
5. web -> Access to database1 and database2
You can download the code in the following link:
GitHub Project
I've configure both datasource in this way:
- database1:
package rc.persistence;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(entityManagerFactoryRef = "hotelEntityManagerFactory", transactionManagerRef = "hotelTransactionManager", basePackages = {
"rc.repository" }) //Mirar si se puede sustituir por rc.domain o rc.repository
public class HotelDbConfig {
#Autowired
private Environment env;
#Bean(name = "hotelDataSource")
#ConfigurationProperties(prefix = "hoteles.datasource")
public DataSource customDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getProperty("hoteles.datasource.driver-class-name"));
dataSource.setUrl(env.getProperty("hoteles.datasource.url"));
dataSource.setUsername(env.getProperty("hoteles.datasource.username"));
dataSource.setPassword(env.getProperty("hoteles.datasource.password"));
return dataSource;
}
#Bean(name = "hotelEntityManagerFactory")
public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder,
#Qualifier("hotelDataSource") DataSource dataSource) {
return builder.dataSource(dataSource).packages("rc.domain")
.persistenceUnit("hotel").build();
}
#Bean(name = "hotelTransactionManager")
public PlatformTransactionManager transactionManager(
#Qualifier("hotelEntityManagerFactory") EntityManagerFactory entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}
}
database2:
package rc.persistence2;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(entityManagerFactoryRef = "cocheEntityManagerFactory", transactionManagerRef = "cocheTransactionManager", basePackages = {
"rc.repository2" })
public class CocheDbConfig {
#Autowired
private Environment env;
#Primary
#Bean(name = "cocheDataSource")
#ConfigurationProperties(prefix = "coches.datasource")
public DataSource customDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getProperty("coches.datasource.driver-class-name"));
dataSource.setUrl(env.getProperty("coches.datasource.url"));
dataSource.setUsername(env.getProperty("coches.datasource.username"));
dataSource.setPassword(env.getProperty("coches.datasource.password"));
return dataSource;
}
#Primary
#Bean(name = "cocheEntityManagerFactory")
public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder,
#Qualifier("cocheDataSource") DataSource dataSource) {
return builder.dataSource(dataSource).packages("rc.domain2")
.persistenceUnit("coche").build();
}
#Primary
#Bean(name = "cocheTransactionManager")
public PlatformTransactionManager transactionManager(
#Qualifier("cocheEntityManagerFactory") EntityManagerFactory entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}
}
But when I try to use repositories from web module:
package rc.web;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import rc.domain2.Coche;
import rc.persistence2.CocheRepository;
#RestController
public class CocheController {
#Autowired
private CocheRepository cocheRepository;
public CocheController(CocheRepository cocheRepository) {
this.cocheRepository = cocheRepository;
}
#GetMapping(value = "/coches")
public List<Coche> getCoches() {
List<Coche> hotels = this.cocheRepository.findAll();
return hotels;
}
}
It shows me the following error:
I've tried differents possibilities but always the same result:
2018-09-27 17:08:58.399 WARN 15272 --- [ main]
ConfigServletWebServerApplicationContext : Exception encountered
during context initialization - cancelling refresh attempt:
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'cocheController' defined in file
[C:\springboot-multiple-maven-modules\web\target\classes\rc\web\CocheController.class]:
Unsatisfied dependency expressed through constructor parameter 0;
nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type 'rc.persistence2.CocheRepository' available:
expected at least 1 bean which qualifies as autowire candidate.
Dependency annotations: {} 2018-09-27 17:08:58.399 INFO 15272 --- [
main] j.LocalContainerEntityManagerFactoryBean : Closing JPA
EntityManagerFactory for persistence unit 'coche' 2018-09-27
17:08:58.400 INFO 15272 --- [ main]
j.LocalContainerEntityManagerFactoryBean : Closing JPA
EntityManagerFactory for persistence unit 'hotel' 2018-09-27
17:08:58.403 INFO 15272 --- [ main]
o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2018-09-27 17:08:58.421 INFO 15272 --- [ main]
ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report
re-run your application with 'debug' enabled. 2018-09-27 17:08:58.670
ERROR 15272 --- [ main]
o.s.b.d.LoggingFailureAnalysisReporter :
*************************** APPLICATION FAILED TO START
Description:
Parameter 0 of constructor in rc.web.CocheController required a bean
of type 'rc.persistence2.CocheRepository' that could not be found.
Action:
Consider defining a bean of type 'rc.persistence2.CocheRepository' in
your configuration.
Please help!!
Thanks in advance!
You got a error in the datasource configuration. Your CocheDbConfig datasource is scanning in the based packages "rc.repository2" to find out Repository class so it can't find the bean 'rc.persistence2.CocheRepository' in your controller.
You should change the based packages in your database2 datasource like this
#EnableJpaRepositories(entityManagerFactoryRef = "cocheEntityManagerFactory", transactionManagerRef = "cocheTransactionManager", basePackages = {
"rc.persistence2" })

Gradle Error in contextLoads under test

i am trying to build a web using Spring and Angular Js tegether w/ Gradle. my problem is When i run my project or build gradle this error comes out.
"contextLoads FAILED"
"What went Wrong:"
.> There were failing tests.: /build/reports/tests/test/index.html
Caused by:
org.springframework.beans.factory.UnsatisfiedDependencyException
Caused by:
org.springframework.beans.factory.NoSuchBeanDefinitionException
ContextLoad Leads me to this Class:
package com.linkedin.learning.linkedinlearningfullstackappangularspringboot;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
#RunWith(SpringRunner.class)
#SpringBootTest
public class LinkedInLearningFullStackAppAngularSpringBootApplicationTests {
#Test
public void contextLoads() {
}
}
heres the screenshot to make it clearer:
enter image description here

Why I am getting NoSuchBeanDefinitionException when I deploy my Spring application in Tomcat?

I am working with Spring and Spring Data JPA. When deploying my application in Tomcat I'm getting the following exception:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name
'myController': Injection of autowired dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Could not autowire field:
private com.service.MyService com.controller.MyController.myService; nested exception
is org.springframework.beans.factory.BeanCreationException: Error creating bean with name
'MyService': Injection of autowired dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Could not autowire field:
private com.repository.MyRepository com.service.MyService.myRepository; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type
[com.repository.MyRepository] found for dependency: expected at least 1 bean which qualifies
as autowire candidate for this dependency. Dependency annotations:
{#org.springframework.beans.factory.annotation.Autowired(required=true)}
The following are my code:
MyController.java
package com.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.domain.MyEntity;
import com.service.MyService;
#RestController
#RequestMapping(MyController.ROOT_RESOURCE_PATH)
public class MyController{
public static final String ROOT_RESOURCE_PATH = "/test";
#Autowired
private MyService myService;
#RequestMapping(value="/list", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public List<MyEntity> getAll() {
return myService.getAll();
}
}
MyService.java
package com.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.domain.MyEntity;
import com.repository.MyRepository;
#Service(value = "MyService")
public class MyService {
#Autowired
private MyRepository myRepository;
public List<MyEntity> getAll() {
return myRepository.findAll();
}
}
MyRepository.java
package com.repository;
import java.util.List;
import org.springframework.data.repository.Repository;
import com.domain.MyEntity;
public interface MyRepository extends Repository<MyEntity, Long> {
public List<MyEntity> findAll();
}
}
MyApplication-context.xml
<jpa:repositories base-package="com.repository" />
<context:component-scan base-package="com.service" />
<context:component-scan base-package="com.controller" />
<context:annotation-config />
I'm not seeing your repository annotated. That might be the reason why Spring couldn't create a bean for MyRepository during component scan. Annotate it with #Repository

Resources