can't receive values from spring cloud config server - java

Using #Value(${fanout.exchange}) annotation failed to init while using a spring-cloud-config server with Github repo.
I'm getting:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'queue' defined in class path resource [com/eloomina/dataCollector/rabbitMQ/RabbitConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.amqp.core.Queue]: Factory method 'queue' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'scopedTarget.rabbitConfiguration': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'fanout.exchange' in value "${fanout.exchange}"
both classes have spring-cloud-config on their pom.xml. configServer is annotated with #EnableConfigServer . my file in the github repo is named dataCollector.properties
RabbitConfiguration class:
#Configuration
#RefreshScope
public class RabbitConfiguration {
#Value("${fanout.exchange}")
private String rawDataExchange;
#Value("${queue.name}")
private String queueName;
#Bean
Queue queue() {
return new Queue(queueName, true);
}
#Bean
FanoutExchange exchange() {
return new FanoutExchange(rawDataExchange);
}
#Bean
Binding binding(Queue queue, FanoutExchange exchange) {
return BindingBuilder.bind(queue).to(exchange);
}
}
my config server application.properties:
server.port=8888
eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka
spring.application.name=configServer
spring.cloud.config.server.git.uri=https://github.com/eLoomina/configFiles
spring.cloud.config.server.git.username=xxxxxx
spring.cloud.config.server.git.password=xxxxxx
my client bootstrap.properties:
spring.application.name=dataCollector 
spring.cloud.config.uri=http://localhost:8888
management.security.enabled=false
eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka
github repo contain one file: dataCollector.properties :
s
pring.devtools.restart.enabled = false
eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka
server.port=8081
spring.application.name=dataCollector
##MONGO:
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=accounts
management.server.port: 9001
## RABBITMQ
queue.name: rawDataQueue
fanout.exchange: rawdata-exchange
spring.rabbitmq.host: localhost
spring.rabbitmq.port: 5672
spring.rabbitmq.username: guest
spring.rabbitmq.password: guest
##LOGGING:
logging.file=dataCollector.log
any ideas why the dataCollector service won't get fanout.exchange from the config server?

Is your file loaded in spring context? Can you see the file in the log something like below:
INFO 1234 --- [ main] b.c.PropertySourceBootstrapConfiguration :Located property source: CompositePropertySource {name='demoService',
propertySources=[MapPropertySource {name='configClient'},
MapPropertySource
{name='https://github.com/demo-configuration/application.properties'}]}

Related

Using #Document notation in an #Entity

I have entities marked with the #Entity notation for jpa, such as
#AllArgsConstructor
#NoArgsConstructor
#Entity
#Table(name = "category", schema = "\"public\"")
public class Category extends AbstractBaseEntity {
...
But I also want to use elastic search repository and for such I need to use the #Document notation, however, if I use both I get an exception:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'categoryController': Unsatisfied dependency expressed through field 'categoryService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'categoryServiceImpl': Unsatisfied dependency expressed through field 'elasticsearchRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'categoryElasticSearchRepository' defined in br.com.gwcloud.smartplace.catalog.elasticsearch.repositories.CategoryElasticSearchRepository defined in #EnableElasticsearchRepositories declared on ElasticSearchConfig: Invocation of init method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.elasticsearch.repository.support.SimpleElasticsearchRepository]: Constructor threw exception; nested exception is org.springframework.dao.DataAccessResourceFailureException: 5,000 milliseconds timeout on connection http-outgoing-0 [ACTIVE]; nested exception is java.lang.RuntimeException: 5,000 milliseconds timeout on connection http-outgoing-0 [ACTIVE]
My configuration file is as following:
#Configuration
#EnableElasticsearchRepositories("br.com.gwcloud.smartplace.catalog.elasticsearch.repositories")
public class ElasticSearchConfig {
#Bean
public RestHighLevelClient client() {
ClientConfiguration clientConfiguration
= ClientConfiguration.builder()
.connectedTo("localhost:9200")
.build();
return RestClients.create(clientConfiguration).rest();
}
#Bean
public ElasticsearchOperations elasticsearchTemplate() {
return new ElasticsearchRestTemplate(client());
}
}
Looking at the error message it's pretty obvious what the problem is:
java.net.ConnectException: Connection refused
When you put #Document on your entity, Spring Data Elasticsearch tries to initialize the repository and tries to connect to the Elasticsearch cluster.
Either your configuration is wrong or not existent, in the latter case Spring Data Elasticsearch tries to connect to a local instance running at localhost:9200.

Spring WebMVC with Data and Couchbase - Error creating bean when trying to inject as service

I just started to work with Spring. I followd some tutorials to create a Spring Web MVC project which works. It is a simple project which displays some information as website using thymeleaf.
Now I wanted to add a couchbase database for storing data, I already worked with couchbase for simple .Net Apps. So I followed the tutorial on the official couchbase blog to create a service for the connection to couchbase. Couchbase with Spring-Boot and Spring Data
But when I try to autowire the service I get the following error message:
[main] INFO org.springframework.web.servlet.DispatcherServlet - Initializing Servlet 'dispatcher'
[main] INFO org.springframework.data.repository.config.RepositoryConfigurationDelegate - Multiple Spring Data modules found, entering strict repository configuration mode!
[main] INFO org.springframework.data.repository.config.RepositoryConfigurationDelegate - Bootstrapping Spring Data repositories in DEFAULT mode.
[main] INFO org.springframework.data.repository.config.RepositoryConfigurationDelegate - Finished Spring Data repository scanning in 70ms. Found 1 repository interfaces.
[main] WARN org.springframework.web.context.support.AnnotationConfigWebApplicationContext - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'indexController': Unsatisfied dependency expressed through field 'buildingService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.xplorg.model.BuildingService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
[main] ERROR org.springframework.web.servlet.DispatcherServlet - Context initialization failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'indexController': Unsatisfied dependency expressed through field 'buildingService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.xplorg.model.BuildingService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
As far as I understand the message, found Spring the repository but it does not qualify as autowire candidate.
My WebConfig:
#Configuration
#EnableWebMvc
#ComponentScan("com.project.controller")
#ComponentScan("com.xplorg.model")
#EnableCouchbaseRepositories(basePackages = {"com.project.model"})
public class MvcWebConfig implements WebMvcConfigurer {
// Code for generating templateEngine/Resolver ...
}
My controller (here I try to autowire the service, not sure if it is the correct place, causes the exception):
#Controller
public class IndexController {
private int count = 0;
#Autowired
private BuildingService buildingService;
// This line causes the exception
#GetMapping("/")
public String index(Model model) {
model.addAttribute("message", "Welcome to Hello World");
return "index";
}
// Some more mapping no use of service
}
My BuildingService:
public interface BuildingService {
Building save(Building building);
Building findById(String buildingId);
List<Building> findByCompanyId(String companyId);
Building findByCompanyAndAreaId(String companyId, String areaId);
List<Building> findByCompanyIdAndNameLike(String companyId, String name, int page);
List<Building> findByPhoneNumber(String telephoneNumber);
Long countBuildings(String companyId);
}
My BuildingServiceImpl:
#Service("BuildingService")
public class BuildingServiceImpl implements BuildingService {
#Autowired
private BuildingRepository buildingRepository;
#Override
public List<Building> findByCompanyId(String companyId) {
return buildingRepository.findByCompanyId(companyId);
}
public List<Building> findByCompanyIdAndNameLike(String companyId, String name, int page) {
return buildingRepository.findByCompanyIdAndNameLikeOrderByName(companyId, name, new PageRequest(page, 20))
.getContent();
}
#Override
public Building findByCompanyAndAreaId(String companyId, String areaId) {
return buildingRepository.findByCompanyAndAreaId(companyId, areaId);
}
#Override
public List<Building> findByPhoneNumber(String telephoneNumber) {
return buildingRepository.findByPhoneNumber(telephoneNumber);
}
#Override
public Building findById(String buildingId) {
return buildingRepository.findById(buildingId).get();
}
#Override
public Building save(Building building) {
return buildingRepository.save(building);
}
#Override
public Long countBuildings(String companyId) {
return buildingRepository.countBuildings(companyId);
}
}
The order classes are simple copied from the tutorial.
Project sturcture:
src/main/java
com.project
config
MvcWebApplicationInitializer
MvcWebConfig
controller
IndexController
model
Area
Building
BuildingRepository
BuildingService
BuildingServiceImpl
EDIT
At the end of the error message the following line stands, could that mean I am missing a dependency?
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'couchbaseRepositoryOperationsMapping' available
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:769)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1221)
EDIT 2
After trying different approaches and reading more about Spring/Couchbase and Autowired, I now get the exception that No bean named 'couchbaseRepositoryOperationsMapping' available. The whole exception looks like this:
[main] INFO org.springframework.web.servlet.DispatcherServlet - Initializing Servlet 'dispatcher'
[main] INFO org.springframework.data.repository.config.RepositoryConfigurationDelegate - Bootstrapping Spring Data repositories in DEFAULT mode.
[main] INFO org.springframework.data.repository.config.RepositoryConfigurationDelegate - Finished Spring Data repository scanning in 63ms. Found 1 repository interfaces.
[main] WARN org.springframework.web.context.support.AnnotationConfigWebApplicationContext - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'buildingServiceImpl': Unsatisfied dependency expressed through field 'buildingRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'buildingRepository': 'buildingRepository' depends on missing bean 'couchbaseRepositoryOperationsMapping'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'couchbaseRepositoryOperationsMapping' available
[main] ERROR org.springframework.web.servlet.DispatcherServlet - Context initialization failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'buildingServiceImpl': Unsatisfied dependency expressed through field 'buildingRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'buildingRepository': 'buildingRepository' depends on missing bean 'couchbaseRepositoryOperationsMapping'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'couchbaseRepositoryOperationsMapping' available
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:596)

Override default RestTemplate in Spring Boot 2.1.1

I'm using Spring Boot 2.1.1, Spring Data REST, Spring HATEOAS, Hibernate.
In my #Configuration class I created a custom RestTemplate:
#Configuration
#EnableRetry
#EnableTransactionManagement
#EnableJpaAuditing(auditorAwareRef = "springSecurityAuditorAware")
public class CustomConfiguration {
#Bean
public RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplateBuilder().setConnectTimeout(httpClientConnectionTimeout)
.setReadTimeout(httpClientReadTimeout).build();
ObjectMapper objectMapper = new ObjectMapper();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter(objectMapper));
restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));
return restTemplate;
}
I use this restTemplate in a #Component:
#Component
public class TenantRestClient {
#Autowired
private RestTemplate restTemplate;
public Tenant register(Tenant tenant) {
//my stuff here
}
Until Spring Boot 2.0.3 everything worked fine, but if I update to Spring 2.0.4 or greater, when I try to run my application I've this exception:
14/12/2018 09:09:55,442 INFO main testServerApplication:50 - Starting testServerApplication on SVILUPPO1 with PID 10612 (C:\Users\Daniele\Documents\workspaceREST2\test-server\target\classes started by Daniele in C:\Users\Daniele\Documents\workspaceREST2\test-management-server)
14/12/2018 09:09:55,448 DEBUG main testServerApplication:53 - Running with Spring Boot v2.1.1.RELEASE, Spring v5.1.3.RELEASE
14/12/2018 09:09:55,448 INFO main testServerApplication:679 - The following profiles are active: prod
14/12/2018 09:10:02,101 ERROR main TomcatStarter:62 - Error starting Tomcat context. Exception: org.springframework.beans.factory.UnsatisfiedDependencyException. Message: Error creating bean with name 'webSecurityConfiguration': 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 'webMvcConfiguration': Unsatisfied dependency expressed through field 'tenantRestClient'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'tenantRestClient': Unsatisfied dependency expressed through field 'restTemplate'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'restTemplate' defined in class path resource [cloud/test/server/config/CustomConfiguration.class]: Initialization of bean failed; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'org.springframework.hateoas.config.ConverterRegisteringWebMvcConfigurer' available: expected single matching bean but found 2: org.springframework.hateoas.config.ConverterRegisteringWebMvcConfigurer#0,org.springframework.hateoas.config.ConverterRegisteringWebMvcConfigurer#1
14/12/2018 09:10:02,124 WARN main WebappClassLoaderBase:173 - The web application [ROOT] appears to have started a thread named [lettuce-eventExecutorLoop-1-1] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread:
sun.misc.Unsafe.park(Native Method)
java.util.concurrent.locks.LockSupport.parkNanos(LockSupport.java:215)
java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.awaitNanos(AbstractQueuedSynchronizer.java:2078)
java.util.concurrent.LinkedBlockingQueue.poll(LinkedBlockingQueue.java:467)
io.netty.util.concurrent.SingleThreadEventExecutor.takeTask(SingleThreadEventExecutor.java:251)
io.netty.util.concurrent.DefaultEventExecutor.run(DefaultEventExecutor.java:64)
io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:884)
io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
java.lang.Thread.run(Thread.java:748)
14/12/2018 09:10:02,128 WARN main AnnotationConfigServletWebServerApplicationContext:554 - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is org.springframework.boot.web.server.WebServerException: Unable to start embedded Tomcat
14/12/2018 09:10:02,163 ERROR main LoggingFailureAnalysisReporter:42 -
***************************
APPLICATION FAILED TO START
***************************
Description:
Field restTemplate in cloud.test.server.rest.clients.TenantRestClient required a single bean, but 2 were found:
- org.springframework.hateoas.config.ConverterRegisteringWebMvcConfigurer#0: defined in null
- org.springframework.hateoas.config.ConverterRegisteringWebMvcConfigurer#1: defined in null
Action:
Consider marking one of the beans as #Primary, updating the consumer to accept multiple beans, or using #Qualifier to identify the bean that should be consumed
Process finished with exit code 1
I tried to:
Set a #Qualifier on restTemplate in my #Configuration class
Remove the bean restTemplate in my #Configuration class
The first attempt did't change anything, with the latter I've this weir error:
***************************
APPLICATION FAILED TO START
***************************
Description:
Field restTemplate in cloud.test.server.rest.clients.TenantRestClient required a bean of type 'org.springframework.web.client.RestTemplate' that could not be found.
Action:
Consider defining a bean of type 'org.springframework.web.client.RestTemplate' in your configuration.
Do you have any hint to solve this strange error? And...why does it happen just updating to Spring Boot >=2.0.4 (same code)?
Try annotation restTemplate bean with #Primary.
#Bean
#Primary
public RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplateBuilder().setConnectTimeout(httpClientConnectionTimeout)
.setReadTimeout(httpClientReadTimeout).build();
ObjectMapper objectMapper = new ObjectMapper();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter(objectMapper));
restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));
return restTemplate;
}
please try with below property in the application.properties of your spring boot project. Then it will allow you to override the existing bean definitions with our custom with the same name.
spring.main.allow-bean-definition-overriding=true

Spring Boot can't find classpath property from dependency module

I currently have a Spring Boot application with a dependency to a Java module. This Java module has some classpath properties. When I #Autowired a bean from the Java module in my Spring Boot application and define this bean with a #Bean annotation and then run the Spring Boot application it will throw errors.
Error thrown:
2017-02-07 12:16:03.188 WARN 17620 --- [on(4)-127.0.0.1] ationConfigEmbeddedWebApplicationContext :
Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'MyService': Unsatisfied dependency expressed through method 'setClassPathProperty' parameter 0; nested exception is org.springframework.beans.factory.BeanExpressionException: Expression parsing failed; nested exception is org.springframework.expression.spel.SpelEvaluationException: EL1008E: Property or field 'myClassPathProperties' cannot be found on object of type 'org.springframework.beans.factory.config.BeanExpressionContext' - maybe not public?
Property defined in Java Module
src/main/resources/myproject-context.xml
<util:properties id="myClassPathProperties" location="classpath:myproject.properties" />
Property usage in Java Module
#Value("#{myClassPathProperties['property.x']}")
public void setClassPathProperty(String x) {
this.x = x;
}
Bean definition in Spring Boot application
#Bean (name = "mailSubscriptionDao")
public MyService getMyService() {
return new MyServiceImpl();
}
Try to get the whole properties object injected
#Autowired
Properties myClassPathProperties;
If this works, you know you have loaded myproject-context.xml correctly.
Than you can also have a look with the debugger, whether a property with name 'property.x' exists or not.

How to use the SpringBoot's context for testing by JerseyTest

I have some #Component and #Resource in my SpringBoot application.
I have the right JDBC datasource, and also I have some REST services, by Jersey.
I want to test one of the services, but it will fail, it says:
Injection of autowired dependencies failed
But it does not use any component.
This is a simple test for testing db, and it is working:
#RunWith(SpringJUnit4ClassRunner.class)
#SpringApplicationConfiguration(classes = MyApplication.class)
public class CommonRepositoryTest {
#Autowired
private MyRepository myRepository;
#Test
public void testDatabaseChangeLogsSize() {
int resultSize = myRepository.getTableRowSize(MyTable.TABLE_NAME);
System.out.println("MyTable result list size: "+resultSize);
assertTrue("MyTable table should has at least one row!", resultSize>0);
}
}
But this REST tester is not working:
#RunWith(SpringJUnit4ClassRunner.class)
#SpringApplicationConfiguration(classes = MyApplication.class)
public class SampleResourceTest extends JerseyTest {
#Override
protected Application configure() {
ApplicationContext context = new AnnotationConfigApplicationContext(MyApplication.class);
return new ResourceConfig(SampleResource.class).property("contextConfig", context);
}
#Test
public void testSampleGet() throws Exception {
long id = 1;
String name = "name";
SampleDomainModel sampleDomainModel = new SampleDomainModel();
sampleDomainModel.setId(id);
sampleDomainModel.setName(name);
Response response = target("/sampleresource/samplepath/" + id).queryParam(name).request().get(Response.class);
SampleDomainModel responseSampleDomainModel = response.readEntity(SampleDomainModel.class);
assertEquals(sampleDomainModel.getId(), responseSampleDomainModel.getId());
}
}
As you see, it must override the configure() method from JerseyTest.
I think the problam is, that the AnnotationConfigApplicationContext cannot load anything maybe (?).
The #SpringApplicationConfiguration(classes = MyApplication.class) annotation loads the context, but the new AnnotationConfigApplicationContext(MyApplication.class) code maybe do the failure, it does not have the full context.
If I replace the code with mocking, it works (but it is not a nice way):
#Override
protected Application configure() {
ApplicationContext mockContext = Mockito.mock(ApplicationContext.class);
return new ResourceConfig(SampleResource.class).property("contextConfig", mockContext);
}
The fail message is:
2016-05-13 13:25:39.617 WARN 9832 --- [ main] s.c.a.AnnotationConfigApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myRepositoryImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.springframework.jdbc.core.JdbcTemplate com.repository.impl.myRepositoryImpl.jdbcTemplate; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$JdbcTemplateConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private javax.sql.DataSource org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$JdbcTemplateConfiguration.dataSource; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfiguration$NonEmbeddedConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.sql.DataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (no profiles are currently active).
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.422 sec <<< FAILURE! - in com.ws.server.SampleResourceTest
testSampleGetWithCorrectParameters(com.ws.server.SampleResourceTest) Time elapsed: 0.015 sec <<< ERROR!
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myRepositoryImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.springframework.jdbc.core.JdbcTemplate com.repository.impl.MyRepositoryImpl.jdbcTemplate; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$JdbcTemplateConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private javax.sql.DataSource org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$JdbcTemplateConfiguration.dataSource; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfiguration$NonEmbeddedConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.sql.DataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (no profiles are currently active).
at org.springframework.boot.autoconfigure.jdbc.DataSourceProperties.getDriverClassName(DataSourceProperties.java:180)
at org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$NonEmbeddedConfiguration.dataSource(DataSourceAutoConfiguration.java:121)
How to use the SpringBoot context for this jersey test?
SImply put, you can't use both Spring's TestContext and Jersey Test Framework together. They will operate on two different ApplicationContexts. Even if you try to inject the ApplicationContext (created be the TestContext) into the test class and pass it to the ResourceConfig in the configure method, it's too late, as the injection doesn't occur until after construction, but the `configure method is called during contruction.
Forget JerseyTest and just use #WebIntegrationTest. See the sample from the spring boot project.
#RunWith(SpringJUnit4ClassRunner.class)
#SpringApplicationConfiguration(SampleJerseyApplication.class)
#WebIntegrationTest(randomPort = true)
public class SampleJerseyApplicationTests {
#Value("${local.server.port}")
private int port;
In a Jersey/Boot environment, Jersey needs to run in a web app environment, and that's what the #WebIntegrationTest does.
For the client, instead of just calling target on the JerseyTest, you will just need to create the client
Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://localhost:" + this.port);
Response response = target.path("/sampleresource/samplepath/" + id).request().get();

Categories

Resources