failed to load application context in junit with spring 4 annotations - java

I'm using the following POM versions:
<properties>
<endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<springframework.version>4.3.5.RELEASE</springframework.version>
<springsecurity.version>4.0.4.RELEASE</springsecurity.version>
<hibernate.version>4.3.11.Final</hibernate.version>
<mysql.connector.version>5.1.31</mysql.connector.version>
</properties>
.
.
.
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-websocket</artifactId>
<version>4.2.4.RELEASE</version>
</dependency>
.
.
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.1.3.Final</version>
</dependency>
.
.
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.7</version>
</dependency>
and for the test libraries:
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>1.9.5</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>3.2.3.RELEASE</version>
<scope>test</scope>
<type>jar</type>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>2.2.4</version>
</dependency>
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>javax.el</artifactId>
<version>2.2.4</version>
</dependency>
And I have included every class annotated with #Configuration in the #ContextConfiguration(classes={...} annotation, yet I still get the same error could not load application context. I know I have to add every dependency here, so I've added all the classes to the ContextConfiguration and still the same.
I tried to use ComponentScan annotation on a newly created configuration class, and it still the same.
Please note that I am using annotation configurations not xml files.
one of the error many lines:
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hibernateTokenRepositoryImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: org.hibernate.SessionFactory com.company.projectname.dao.AbstractDao.sessionFactory; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in com.company.api.configuration.spirng.HibernateConfiguration: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.hibernate4.LocalSessionFactoryBean]: Factory method 'sessionFactory' threw exception; nested exception is java.lang.IllegalStateException: #Bean method HibernateConfiguration.dataSource called as a bean reference for type [javax.sql.DataSource] but overridden by non-compatible bean instance of type [com.company.projectname.model.DataSource]. Overriding bean of same name declared in: null
And here is one of the #Configuration classes:
#Configuration
#EnableWebMvc
#EnableScheduling
#ComponentScan(basePackages = {"com.company.api", "com.company.project"})
public class SpringConfiguration extends WebMvcConfigurerAdapter {
/**
* Added #Lazy to prevent using messageSource in UserService before its
* being created here
*/
#Autowired
#Lazy
RoleConverter roleConverter;
/**
* Added #Lazy to prevent using messageSource in UserService before its
* being created here
*/
#Autowired
#Lazy
ReportConverter reportConverter;
/**
* Added #Lazy to prevent using messageSource in UserService before its
* being created here
*/
#Autowired
#Lazy
GroupConverter groupConverter;
#Autowired
#Lazy
ReportStyleConverter reportStyleConverter;
#Autowired
#Lazy
LanguageConverter languageConverter;
#Autowired
#Lazy
UserProfileNotificationEventConverter userProfileNotificationEventConverter;
#Autowired
private ContextHolder context;
.
.
.
Other beans and functions
}

Related

Quarkus Unsatisfied dependency for type. Using Extension

I have next structure:
Quarkus extension 'core' with interface SomeInterface and bean SomeContainer:
#ApplicationScoped
public class SomeContainer {
#Inject
SomeInterface someInterface;
}
Quarkus extension 'implementation' with SomeImpl bean:
#ApplicationScoped
public class SomeImpl implements SomeInterface {
}
Quarkus application - 'starter' which depend quarkus extension 'implementation' and jax rs controller:
#Path("/hello")
public class GreetingResource {
#Inject
SomeContainer someContainer;
#GET
#Produces(MediaType.TEXT_PLAIN)
public String hello() {
}
}
When I try start app I get an error:
Caused by: javax.enterprise.inject.spi.DeploymentException: javax.enterprise.inject.UnsatisfiedResolutionException: Unsatisfied dependency for type by.test.core.SomeInterface and qualifiers [#Default]
How to fix it?
link to project https://github.com/flagmen/quarkus-test
Your starter module only depends on the core module which by itself does not contain a CDI injectable candidate for the SomeInterface.
You should add the implementation module holding the discoverable bean as a dependency as well:
<!-- quarkus-test/starter/pom.xml -->
<dependencies>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-resteasy</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-junit5</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>by.test</groupId>
<artifactId>core</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>by.test</groupId>
<artifactId>implementation</artifactId> <!-- you can even omit the core module as it will be transitively imported -->
<version>1.0.0</version>
</dependency>
</dependencies>

Spring Boot: HATEOAS and custom JacksonObjectMapper

After I added dependency for HATEOAS to Maven, Spring Boot does not start:
Added dependency:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-hateoas</artifactId>
</dependency>
Full pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>ru.example</groupId>
<artifactId>testapp</artifactId>
<version>1.0</version>
<name>testapp</nAfter I added dependency for HATEOAS to Maven, Spring Boot does not startame>
<description>Test</description>
<properties>
<java.version>1.8</java.version>
<h2.version>1.4.200</h2.version>
<jackson-json.version>2.10.2</jackson-json.version>
<jsoup.version>1.12.1</jsoup.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-hateoas</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.17.Final</version>
</dependency>
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>${jsoup.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<version>5.3.0.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>${h2.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson-json.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-hibernate5</artifactId>
<version>${jackson-json.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>${jackson-json.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
SecurityConfig.class:
package ru.example.testapp;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import ru.example.testapp.dao.UserRepository;
import ru.example.testapp.service.UserServiceImpl;
#Configuration
#RequiredArgsConstructor
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private final UserRepository userRepository;
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(new UserServiceImpl(userRepository))
.passwordEncoder(new BCryptPasswordEncoder());
}
protected void configure(final HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/rest/admin/**").hasRole("ADMIN").and().httpBasic().and()
.authorizeRequests()
.antMatchers("/rest/user/**").hasAnyRole("USER","ADMIN").and().httpBasic().and()
.authorizeRequests().and()
.csrf().ignoringAntMatchers("/rest/**");
}
}
JacksonObjectMapper.class:
package ru.example.testapp.util.json;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.hibernate5.Hibernate5Module;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.stereotype.Component;
#Component
public class JacksonObjectMapper extends ObjectMapper {
private static final ObjectMapper MAPPER = new JacksonObjectMapper();
public static ObjectMapper getMapper() {
return MAPPER;
}
private JacksonObjectMapper() {
registerModule(new Hibernate5Module());
registerModule(new JavaTimeModule());
configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE);
setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
setSerializationInclusion(JsonInclude.Include.NON_NULL);
}
}
In console I have following error:
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'securityConfig': Unsatisfied dependency
expressed through method 'setContentNegotationStrategy' parameter 0;
nested exception is
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name
'org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration$EnableWebMvcConfiguration':
Unsatisfied dependency expressed through method 'setConfigurers'
parameter 0; nested exception is
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'hypermediaWebMvcConfigurer' defined in
class path resource
[org/springframework/hateoas/config/WebMvcHateoasConfiguration.class]:
Unsatisfied dependency expressed through method
'hypermediaWebMvcConfigurer' parameter 0; nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'hypermediaWebMvcConverters' defined in class
path resource
[org/springframework/hateoas/config/HateoasConfiguration.class]: Bean
instantiation via factory method failed; nested exception is
org.springframework.beans.BeanInstantiationException: Failed to
instantiate [org.springframework.hateoas.config.WebConverters]:
Factory method 'hypermediaWebMvcConverters' threw exception; nested
exception is java.lang.IllegalStateException: Failed copy():
ru.example.wmanage.util.json.JacksonObjectMapper (version: 2.10.2)
does not override copy(); it has to
What could be the problem?
In error - something with securityConfig, JacksonObjectMapper and hateoas.
If I delete spring-boot-starter-hateoas at dependencies, then all works. But I need hateoas.
Please help.
UPDATED:
The problem occurs when using custom JacksonObjectMapper with annotation #Component. As soon as spring-boot-starter-hateoas added to dependencies, then Spting Boot does not startup.
QUESTION: How to use custom JacksonObjectMapper and hateoas together?
PROBLEM NOT RESOLVED
I don't think you have any reason to be extending ObjectMapper. You should instantiate an ObjectMapper like normal and then configure it by its exposed methods and register it as a bean in your configuration.
#Bean
public ObjectMapper createMapper() {
return new ObjectMapper().registerModule(new Hibernate5Module());
.registerModule(new JavaTimeModule());
.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE);
.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
.setSerializationInclusion(JsonInclude.Include.NON_NULL);
}
I dont know why one should not extend ObjectMapper.
probably Deadron Mar can explain, but this class is not final.
In my case it is extended deeply in our corporal framework and i got same error message.
i just did another extension
#Component
public class MyCustomizedMapper extends AnotherExtendedMapper {
public MyCustomizedMapper copy() {
return new MyCustomizedMapper(); // we have default constructor for this
` }
}
and wonder - it works)

How to fix Error creating bean with name 'requestMappingHandlerMapping'

I'm creating a web application using spring-boot with annotation based configuration.
At first, I created a spring application with annotation based config using Hibernate and JPA. It was working fine but then I needed to add spring-boot to my application and now cannot start it. Here is the code:
#SpringBootApplication
#EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
public class Runner {
public static void main(String[] args) {
SpringApplication.run(Runner.class, args);
}
}
#Configuration
#EnableTransactionManagement
#ComponentScans(value = { #ComponentScan("com.alex.pharm.dao"),
#ComponentScan("com.alex.pharm.service") })
public class AppConfig {
#Bean
public LocalEntityManagerFactoryBean geEntityManagerFactoryBean() {
LocalEntityManagerFactoryBean factoryBean = new LocalEntityManagerFactoryBean();
factoryBean.setPersistenceUnitName("LOCAL_PERSISTENCE");
return factoryBean;
}
#Bean
#ConditionalOnMissingBean(type = "JpaTransactionManager")
public JpaTransactionManager geJpaTransactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(geEntityManagerFactoryBean().getObject());
return transactionManager;
}
}
#RestController
public class HelloController {
#RequestMapping("/")
public String index() {
return "Greetings from Spring Boot!";
}
}
<groupId>com.sachatol.pharmacy</groupId>
<artifactId>pharmacyWebStore</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.5.RELEASE</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.1</version>
</dependency><!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.13</version>
</dependency>
<!-- Hibernate 5.2.9 Final -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.9.Final</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<!-- Spring ORM -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.1.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<build>
<sourceDirectory>src/main/java</sourceDirectory>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
But when I try to run it I get the following exception:
ConfigServletWebServerApplicationContext : Exception encountered during context initialization
- cancelling refresh attempt:org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'requestMappingHandlerMapping'
defined in class path resource
[org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]:
Initialization of bean failed; nested exception is java.lang.NoSuchMethodError:
org.springframework.web.servlet.handler.AbstractHandlerMapping.obtainApplicationContext()
Lorg/springframework/context/ApplicationContext;
How can I fix it?
Issue found - I used the old version for spring-context in pom (4.3.7.RELEASE) which override the one that spring-boot has and was the reason of NoSuchMethodError. So spring-context dependency was old and obsolete after removing or changing it to newer version (5.0.3) application started fine
Your #RequestMapping seems missing some parts, try with something like that:
#RequestMapping(value = "/", method = RequestMethod.GET)
This also happens if you have two methods with same request mapping values. Make sure you have unique RequestMapping values.
In your request mapping, you have incorrectly used :
#RequestMapping("/")
Instead, use this mapping to specify the end-point and the request-method like this :
#RequestMapping(value = "/", method = RequestMethod.GET)
Hope it will solve your problem.

Spring:Connect Sql server from spring boot service

I have rest crud service which will help me make post and get requests and receive respopnses from sql server , inside my application.properties i use similar data:
server.port=9004
spring.datasource.url=jdbc:sqlserver://localhost/1433;databaseName=test1
spring.datasource.username=sa
spring.datasource.password=*****
spring.datasource.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.jpa.show-sql=true
spring.jpa.hibernate.dialect=org.hibernate.dialect.SQLServer2014Dialect
spring.jpa.hibernate.ddl-auto =ddl-auto
AND HERE IS MY POM:
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.6.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>sqljdbc4</artifactId>
<version>4.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
when i run this as a java project i alway got this error:
Caused by: org.springframework.beans.factory.BeanCreationException:
Could not autowire field: private
org.springframework.boot.autoconfigure.web.HttpMessageConverters
org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter.messageConverters;
nested exception is
and:
with name 'mappingJackson2HttpMessageConverter' defined in class path
resource
[org/springframework/boot/autoconfigure/web/JacksonHttpMessageConvertersConfiguration$MappingJackson2HttpMessageConverterConfiguration.class]:
Unsatisfied dependency expressed through constructor argument with
index 0 of type [com.fasterxml.jackson.databind.ObjectMapper]: Error
creating bean with name 'objectMapper' defined in class path resource
[org/springframework/boot/autoconfigure/data/rest/SpringBootRepositoryRestMvcConfiguration.class]:
Bean instantiation via factory method failed; nested exception is
org.springframework.beans.BeanInstantiationException: Failed to
instantiate [com.fasterxml.jackson.databind.ObjectMapper]: Factory
method 'objectMapper' threw exception; nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'config' defined in class path resource
[org/springframework/boot/autoconfigure/data/rest/SpringBootRepositoryRestMvcConfiguration.class]:
Bean instantiation via factory method failed; nested exception is
org.springframework.beans.BeanInstantiationException: Failed to
instantiate
[org.springframework.data.rest.core.config.RepositoryRestConfiguration]:
Factory method 'config' threw exception; nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'resourceMappings' defined in class path
resource
[org/springframework/boot/autoconfigure/data/rest/SpringBootRepositoryRestMvcConfiguration.class]:
Bean instantiation via factory method failed; nested exception is
what should i change inside my pom or properties file to make my program work?
SQL Server dependency is deprecated, use following to interact with SQL Server
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>6.1.0.jre8</version>
</dependency>
follow links for more information
Configuring Spring Boot for Microsoft SQL Server
Open sourcing the Microsoft JDBC Driver and Maven support
Since it is a REST app, need to add the spring-boot-starter-web dependency in pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>sqljdbc4</artifactId>
<version>4.0</version>
</dependency>
Add also connection properties in config (application.properties by default):
spring.datasource.url=jdbc:sqlserver://localhost;databaseName=springbootdb
spring.datasource.username=sa
spring.datasource.password=replace_value
spring.datasource.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.jpa.show-sql=true
spring.jpa.hibernate.dialect=org.hibernate.dialect.SQLServer2012Dialect
spring.jpa.hibernate.ddl-auto = create-drop
Try that one and see if you can build/run the project.
Change your url parameter to:
spring.datasource.url=jdbc:sqlserver://localhost:1433;databaseName=test1
Port number must be preceded by a colon(":"), not slash("/").

NoSuchBeanDefinitionException: No qualifying bean of type '<package>' available: expected at least 1 bean which qualifies as autowire candidate

I have a spring boot application and I am writing an integration test class.
When I run my test class, I get the following exception
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.whot.dao.HotspotDao' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1466) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1097) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1059) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:589) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
I have searched for a while and looked for clues as to what might be causing this but I have not been able to come up with the reason this happens. Help would be appreciated. I have included some details of my code.
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>${spring.boot.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<version>${spring.boot.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<version>${spring.boot.version}</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>${psql.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<version>${spring.boot.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>${spring.boot.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
<version>${spring.boot.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
</dependencies>
I have this in my Application.Java class
package com.whot;
#SpringBootApplication
#ComponentScan(basePackages = {"com.whot.controller"})
#EntityScan(basePackages = {"com.whot.entity"})
#EnableJpaRepositories(basePackages = {"com.whot.repository", "com.whot.dao"})
public class Application extends SpringBootServletInitializer {
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
}
and in my integration class
package com.whot.dao;
#RunWith(SpringRunner.class)
#DataJpaTest
#AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
public class HotspotDaoIntegrationTest {
#Autowired
private HotspotDao hotspotDao;
#Autowired
private TestEntityManager entityManager;
private String hotspotName = "Mavericks";
#Test
public void givenHotspotNameReturnHotspotSuccessfully(){
Address address = new Address("Allen Mgba Crescent", 30L);
entityManager.persist(address);
Hotspot hotspot = new Hotspot(hotspotName);
entityManager.persist(hotspot);
entityManager.flush();
HotspotLocation hsLocation = new HotspotLocation(address);
hsLocation.setHotspotId(hotspot.getId());
entityManager.persist(hsLocation);
hotspot.getHotspotLocations().add(hsLocation);
HotspotDTO hotspotDto =((ArrayList<HotspotDTO>) hotspotDao.getHotspotByName(hotspotName)).get(0);
assertEquals(hotspotDto.getId(), hotspot.getId());
assertEquals(hotspotDto.getName(), hotspot.getName());
}
}
and the class in question here
package com.whot.dao;
#Component
public class HotspotDao {
#Autowired
HotspotRespository hsRepository;
public Collection<HotspotDTO> getHotspotByName(String hotspotName) {
Collection <HotspotDTO> hotspots = getHotspotsByName(Arrays.asList(hotspotName));
return hotspots;
}
public Collection<HotspotDTO> getHotspotsByName(Collection <String> names) {
Collection<Hotspot> hotspots = hsRepository.findHotspotsByName(names);
Collection<HotspotDTO> result = new ArrayList<>();
for(Hotspot hotspot: hotspots){
result.add(new HotspotDTO().toHotspotDto(hotspot));
}
return result;
}
}
Spring Boot default scan will start the same package and subpackers with startup application class.
If the other annotation is not in the same package, it will not be able to scan, the solution is to use the #ComponentScan annotation on startup application class, declare the package scan path. like...
#ComponentScan(basePackages={"com.exp.package1","com.exp.package2"})

Categories