Spring Batch test fails after completion because context is not active - java

I have created a simple job in Spring Batch with Spring Boot to be executed as a task with Spring Cloud Task (all in STS4). If I execute it as a Spring Boot App, te execution is correct and without problems, but if I compile the project or try to launch the test, the execution of the job is correct:
o.s.c.t.b.l.TaskBatchExecutionListener : The job execution id 19 was run within the task execution 56
o.s.batch.core.job.SimpleStepHandler : Executing step: [step1]
com.example.demo.MyTasklet : Executing Tasklet: STEP 1
o.s.batch.core.step.AbstractStep : Step: [step1] executed in 16ms
o.s.batch.core.job.SimpleStepHandler : Executing step: [step2]
com.example.demo.MyTasklet : Executing Tasklet: STEP 2
o.s.batch.core.step.AbstractStep : Step: [step2] executed in 7ms
o.s.b.c.l.support.SimpleJobLauncher : Job: [FlowJob: [name=job2]] completed with the following parameters: [{run.id=7, -spring.output.ansi.enabled=always}] and the following status: [COMPLETED] in 52ms
com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated...
com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.
com.zaxxer.hikari.HikariDataSource : HikariPool-2 - Shutdown initiated...
com.zaxxer.hikari.HikariDataSource : HikariPool-2 - Shutdown completed.
But after that, it happends an exception:
o.s.test.context.TestContextManager : Caught exception while allowing TestExecutionListener [org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener#576d5deb] to prepare test instance [com.example.demo.DemoJobApplicationTests#173ed316]
java.lang.IllegalStateException: The ApplicationContext loaded for [[MergedContextConfiguration#e350b40 testClass = DemoJobApplicationTests, locations = '{}', classes = '{class com.example.demo.DemoJobApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer#5e82df6a, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer#50a638b5, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer#0, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer#130161f7, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer#0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer#479d31f3], contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]]] is not active. This may be due to one of the following reasons: 1) the context was closed programmatically by user code; 2) the context was closed during parallel test execution either according to #DirtiesContext semantics or due to automatic eviction from the ContextCache due to a maximum cache size policy.
at org.springframework.util.Assert.state(Assert.java:94) ~[spring-core-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:127) ~[spring-test-5.2.3.RELEASE.jar:5.2.3.RELEASE]
[...]
This makes that the compilation ends in fail, but the execution in the database is recorded as COMPLETED.
Reviewing the code where the error is generated, in the Spring class called DefaultTestContext:
#Override
public ApplicationContext getApplicationContext() {
ApplicationContext context = this.cacheAwareContextLoaderDelegate.loadContext(this.mergedContextConfiguration);
if (context instanceof ConfigurableApplicationContext) {
#SuppressWarnings("resource")
ConfigurableApplicationContext cac = (ConfigurableApplicationContext) context;
Assert.state(cac.isActive(), () ->
"The ApplicationContext loaded for [" + this.mergedContextConfiguration +
"] is not active. This may be due to one of the following reasons: " +
"1) the context was closed programmatically by user code; " +
"2) the context was closed during parallel test execution either " +
"according to #DirtiesContext semantics or due to automatic eviction " +
"from the ContextCache due to a maximum cache size policy.");
}
return context;
}
... the problem is that "context" is not active.
These are my files:
ArqDatasourceConfiguration.java
package com.example.demo;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
#Configuration
public class ArqDatasourceConfiguration {
#Bean
#ConfigurationProperties("spring.batch.datasource")
public DataSource dataSource() throws SQLException {
return DataSourceBuilder.create().build();
}
#Bean
public JdbcTemplate jdbcTemplateBatch(final DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
#Bean(name = "taskDataSource")
#ConfigurationProperties("spring.task.datasource")
public DataSource taskDataSource() throws SQLException {
return DataSourceBuilder.create().build();
}
#Bean
public JdbcTemplate jdbcTemplateTask(#Qualifier("taskDataSource") final DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
}
CustomTaskConfigurer.java
package com.example.demo;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cloud.task.configuration.DefaultTaskConfigurer;
import org.springframework.stereotype.Component;
#Component
public class CustomTaskConfigurer extends DefaultTaskConfigurer {
#Autowired
public CustomTaskConfigurer(#Qualifier("taskDataSource") DataSource dataSource) {
super(dataSource);
}
}
DemoJobApplication.java
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.task.configuration.EnableTask;
#SpringBootApplication
#EnableTask
public class DemoJobApplication {
public static void main(String[] args) {
SpringApplication.run(DemoJobApplication.class, args);
}
}
MyJob.java
package com.example.demo;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
#Configuration
#EnableBatchProcessing
public class MyJob {
#Autowired
public JobBuilderFactory jobBuilderFactory;
#Autowired
public StepBuilderFactory stepBuilderFactory;
#Bean
public Job job2(Step step1, Step step2) {
return jobBuilderFactory.get("job2")
.incrementer(new RunIdIncrementer())
.flow(step1)
.next(step2)
.end()
.build();
}
#Bean
public Step step1() {
return stepBuilderFactory.get("step1")
.tasklet(new MyTasklet("STEP 1"))
.build();
}
#Bean
public Step step2() {
return stepBuilderFactory.get("step2")
.tasklet(new MyTasklet("STEP 2"))
.build();
}
}
MyTasklet.java
package com.example.demo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
public class MyTasklet implements Tasklet {
private static final Logger log = LoggerFactory.getLogger(MyTasklet.class);
private String msg;
public MyTasklet(String msg) {
this.msg = msg;
}
#Override
public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) {
log.info("Executing Tasklet: " + msg);
return RepeatStatus.FINISHED;
}
}
application.properties
spring.batch.initialize-schema=always
spring.main.allow-bean-definition-overriding=true
spring.batch.datasource.jdbc-url=jdbc:postgresql://localhost:5432/postgres
spring.batch.datasource.username=postgres
spring.batch.datasource.password=*****
spring.batch.datasource.driver-class=org.postgresql.Driver
spring.batch.datasource.schema=springbatch
spring.task.datasource.jdbc-url=jdbc:postgresql://localhost:5432/postgres
spring.task.datasource.username=postgres
spring.task.datasource.password=*****
spring.task.datasource.driver-class=org.postgresql.Driver
spring.task.datasource.schema=springtask
DemoJobApplicationTests.java
package com.example.demo;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
#SpringBootTest
class DemoJobApplicationTests {
#Test
void contextLoads() {
}
}
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.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demoJob</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demoJob</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-batch</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</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.springframework.batch</groupId>
<artifactId>spring-batch-test</artifactId>
<scope>test</scope>
</dependency>
<!-- Spring Cloud Task -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-task</artifactId>
<version>1.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-task-core</artifactId>
<version>1.2.2.RELEASE</version>
</dependency>
<!-- ================================== -->
<!-- Database -->
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<!-- ================================== -->
<!-- Warning #ConfigurationProperties -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<!-- ================================== -->
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
I have tried several annotations like #DirtiesContext, #EnableAutoConfiguration, #SpringBatchTest... but nothing seems to solve the issue, so I would appreciate any idea or help.

Well, after some head banging we have found the solution, ant it is really stu...simply. It is necessary to update the version of the dependencies from Spring Cloud Task in the pom.xml, changing 1.2.2.RELEASE with 2.2.2.RELEASE

Related

SpringBoot connection to Redis : Does not appear to be caching data

I am using SpringBoot to connect to Redis. I have Web dependency on SpringBoot and my intention is to write Product information to a runtime datastructure i.e., a Map. I want to test the Cache annotations that Spring provides to understand the usage.
Here is the POM.xml file
<?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.7.0</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>io.fireacademy</groupId>
<artifactId>redisconnectivity</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>redisconnectivity</name>
<description>Demo project for Spring Boot & Redis connectivity</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Here is the Spring Application class
package io.fireacademy.redisconnectivity;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
#SpringBootApplication
#EnableCaching
public class RedisconnectivityApplication {
public static void main(String[] args) {
SpringApplication.run(RedisconnectivityApplication.class, args);
}
}
Here is my main controller class
package io.fireacademy.redisconnectivity.controllers;
import io.fireacademy.redisconnectivity.model.Product;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
#RestController
#RequestMapping("/products")
public class WebAppController {
private static final Logger logger = LoggerFactory.getLogger(WebAppController.class);
// This will serve as the database
private Map<String, Product> m_productDatabase = new HashMap<String, Product>();
#Cacheable(value="my-product-cache", key="#productId")
private Product getProductFromCacheOrDB(String productId)
{
logger.info("Loading the Product " + productId + " from the cache!.");
return m_productDatabase.get(productId);
}
#CacheEvict(value="my-product-cache", key="#productId")
private Product deleteFromCache(String productId)
{
logger.info("Remove the Product " + productId + " from the cache!.");
return m_productDatabase.get(productId);
}
#GetMapping(path="/")
public ResponseEntity<List<Product>> getProducts()
{
Collection<Product> allProducts = m_productDatabase.values();
List<Product> allProductsAsList = allProducts.stream().collect(Collectors.toList());
return new ResponseEntity<List<Product>>(allProductsAsList, HttpStatus.OK);
}
#GetMapping(path="/{productId}")
public ResponseEntity<Product> getProducts(#PathVariable String productId)
{
// Either from the Cache or from the DB.
Product product = getProductFromCacheOrDB(productId);
return new ResponseEntity<Product>(product, HttpStatus.OK);
}
#PostMapping(consumes = {MediaType.APPLICATION_XML_VALUE,MediaType.APPLICATION_JSON_VALUE},
produces = {MediaType.APPLICATION_XML_VALUE,MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<Product> createProduct(#RequestBody Product product)
{
m_productDatabase.put(product.getId(), product);
return new ResponseEntity<Product>(product, HttpStatus.CREATED);
}
#PutMapping(path="/{productId}",
consumes = {MediaType.APPLICATION_XML_VALUE,MediaType.APPLICATION_JSON_VALUE},
produces = {MediaType.APPLICATION_XML_VALUE,MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<Product> updateProduct(#PathVariable String productId, #RequestBody Product product)
{
m_productDatabase.put(productId, product);
return new ResponseEntity<Product>(product, HttpStatus.OK);
}
#DeleteMapping(path="/{productId}")
public ResponseEntity<Product> deleteProduct(#PathVariable String productId)
{
Product deletedProduct = getProductFromCacheOrDB(productId);
deleteFromCache(productId);
return new ResponseEntity<Product>(deletedProduct, HttpStatus.OK);
}
}
Here is my RedisConfig class
package io.fireacademy.redisconnectivity.configurations;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.repository.configuration.EnableRedisRepositories;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
#Configuration
#EnableRedisRepositories
public class RedisConfig {
#Bean
public JedisConnectionFactory connectionFactory() {
RedisStandaloneConfiguration configuration = new RedisStandaloneConfiguration();
configuration.setHostName("localhost");
configuration.setPort(6379);
return new JedisConnectionFactory(configuration);
}
#Bean
public RedisTemplate<String, Object> template() {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(connectionFactory());
template.setKeySerializer(new StringRedisSerializer());
template.setHashKeySerializer(new StringRedisSerializer());
template.setHashKeySerializer(new JdkSerializationRedisSerializer());
template.setValueSerializer(new JdkSerializationRedisSerializer());
template.setEnableTransactionSupport(true);
template.afterPropertiesSet();
return template;
}
}
My application.properties looks as below:
# Redis Config
spring.cache.type=redis
spring.redis.host=localhost
spring.redis.port=6379
And I am running Redis as a docker container using this:
docker run -d -p 6379:6379 --name my-redis redis
When I inspect the docker container's logs, I see nothing happening.
D:\Development\springboot\learn_redis>docker logs -f c376f1be9be35281b900c2943fbf8ea37e1563157efb57d46ca1c74fc880bc5c
1:C 04 Jun 2022 17:49:51.854 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
1:C 04 Jun 2022 17:49:51.854 # Redis version=7.0.0, bits=64, commit=00000000, modified=0, pid=1, just started
1:C 04 Jun 2022 17:49:51.854 # Warning: no config file specified, using the default config. In order to specify a config file use redis-server /path/to/redis.conf
1:M 04 Jun 2022 17:49:51.854 * monotonic clock: POSIX clock_gettime
1:M 04 Jun 2022 17:49:51.858 * Running mode=standalone, port=6379.
1:M 04 Jun 2022 17:49:51.858 # Server initialized
1:M 04 Jun 2022 17:49:51.858 # WARNING overcommit_memory is set to 0! Background save may fail under low memory condition. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect.
1:M 04 Jun 2022 17:49:51.858 * The AOF directory appendonlydir doesn't exist
1:M 04 Jun 2022 17:49:51.858 * Ready to accept connections
My understanding was that the Cache annotations would make the data be stored onto the Redis cache. For instance, the getProductFromCacheOrDB, should store the Product object onto the cache with the input productId as the key because of the #Cacheable annotation and a subsequent call to get this specific Product using the GET productId should not invoke the method again. But this is not happening.
Please show some pointers on what I could have missed...
Thanks,
Pavan.
Edits:
I do not see anything on Redis getting created. I enabled monitoring on Redis via the redis-cli, but see nothing.
I tried removing the RedisConfig class and see no change.
Just created a simple working example at https://github.com/bsbodden/basic-caching-spring-data-redis
What you need:
POM dependencies:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis-reactive</artifactId>
</dependency>
In the app class or configurer #EnableCaching:
#SpringBootApplication
#EnableCaching
public class DemoApplication {
In the app class RedisCacheManager bean:
#Bean
public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) {
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig() //
.prefixCacheNameWith(this.getClass().getPackageName() + ".") //
.entryTtl(Duration.ofHours(1)) //
.disableCachingNullValues();
return RedisCacheManager.builder(connectionFactory) //
.cacheDefaults(config) //
.build();
}
#Cacheable in your controller:
#GetMapping("/{id}")
#Cacheable("some-cache")
public SomeModel get(#PathVariable("id") String id) {
return repo.findById(id).orElse(SomeModel.of("nope"));
}

Could not autowire. No beans of 'JobRepositoryTestUtils' type found. With SpringBatchTest Annotation added

I am working on a Spring Batch unit testing using the #SpringBatchTest annotation which is supposed to automatically add the beans for JobLauncherTestUtils and JobRepositoryTestUtils.
Here's the Job configuration class:
#Configuration
#EnableBatchProcessing
public class JobConfiguration {
#Bean
public Job getJob(JobBuilderFactory jobBuilderFactory,
#Qualifier("flow_master") Flow flowMaster) {
return jobBuilderFactory.get("job")
.incrementer(new RunIdIncrementer())
.start(flowMaster)
.build().build();
}
}
Here's the Test Class:
#ExtendWith(SpringExtension.class)
#SpringBatchTest
#ContextConfiguration(classes = JobConfiguration.class)
public class SpringBatchTest {
#Autowired
private JobLauncherTestUtils jobLauncherTestUtils;
#Before
public void clearJobExecutions() {
this.jobRepositoryTestUtils.removeJobExecutions();
}
#Test
public void testMyJob() throws Exception {
JobParameters jobParameters = this.jobLauncherTestUtils.getUniqueJobParameters();
JobExecution jobExecution = this.jobLauncherTestUtils.launchJob(jobParameters);
Assert.assertEquals(ExitStatus.COMPLETED, jobExecution.getExitStatus());
}
}
Problem:
I am getting the error messages:
Could not autowire. No beans of 'JobLauncherTestUtils' type found.
I have cloned some repo examples which are supposed to work but I am getting the same error for all of them.
Am I missing something?
You did not share your imports but you are probably mixing imports between junit4 and junit5. I'm not able to reproduce your error. Here is a complete example:
The job configuration class:
package com.example.demo;
import javax.sql.DataSource;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
#Configuration
#EnableBatchProcessing
public class MyJobConfig {
#Bean
public Job job(JobBuilderFactory jobs, StepBuilderFactory steps) {
return jobs.get("job")
.start(steps.get("step")
.tasklet((contribution, chunkContext) -> {
System.out.println("Hello world!");
return RepeatStatus.FINISHED;
}).build())
.build();
}
#Bean
public DataSource dataSource() {
return new EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.H2)
.addScript("/org/springframework/batch/core/schema-h2.sql")
.build();
}
public static void main(String[] args) throws Exception {
ApplicationContext context = new AnnotationConfigApplicationContext(MyJobConfig.class);
JobLauncher jobLauncher = context.getBean(JobLauncher.class);
Job job = context.getBean(Job.class);
jobLauncher.run(job, new JobParameters());
}
}
The test class:
package com.example.demo;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.batch.core.ExitStatus;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.test.JobLauncherTestUtils;
import org.springframework.batch.test.JobRepositoryTestUtils;
import org.springframework.batch.test.context.SpringBatchTest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
#ExtendWith(SpringExtension.class)
#SpringBatchTest
#ContextConfiguration(classes = MyJobConfig.class)
class MyJobConfigTest {
#Autowired
private JobLauncherTestUtils jobLauncherTestUtils;
#Autowired
private JobRepositoryTestUtils jobRepositoryTestUtils;
#BeforeEach
public void clearJobExecutions() {
this.jobRepositoryTestUtils.removeJobExecutions();
}
#Test
public void testMyJob() throws Exception {
// given
JobParameters jobParameters = this.jobLauncherTestUtils.getUniqueJobParameters();
// when
JobExecution jobExecution = this.jobLauncherTestUtils.launchJob(jobParameters);
// then
Assertions.assertEquals(ExitStatus.COMPLETED, jobExecution.getExitStatus());
}
}
and the pom.xml file:
<?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>
<groupId>com.example</groupId>
<artifactId>so67767525</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>so67767525</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.batch</groupId>
<artifactId>spring-batch-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.batch</groupId>
<artifactId>spring-batch-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
</plugins>
</build>
<!-- While this has "boot" in the name, it does not bring any Spring Boot feature. -->
<!-- It is used to manage Spring projects dependencies that are known to work correctly together -->
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.4.6</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
</project>
The test runs successfully without the error you mentioned.

Swagger not working with Spring REST API

Hello i am trying to implement swagger with Spring REST, i am not using Spring Boot to create REST API's, i have used normal Spring REST API.
The problem when i run the application and if i navigate to this url
http://localhost:8080/spring-mvc-restfull-crud-example/swagger-ui.html
i am getting only the header of swagger-ui, there is nothing else. I am using Java config instead of XML config.
pom.xml
<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.boraji.tutorial.spring</groupId>
<artifactId>spring-mvc-restfull-crud-example</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<failOnMissingWebXml>false</failOnMissingWebXml>
</properties>
<dependencies>
<!-- Spring MVC Dependency -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<!-- Spring ORM -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<!-- Hibernate ORM -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.11.Final</version>
</dependency>
<!-- Hibernate-C3P0 Integration -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-c3p0</artifactId>
<version>5.2.11.Final</version>
</dependency>
<!-- c3p0 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<!-- Mysql Connector -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.5</version>
</dependency>
<!-- Jackson API for JSON -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.7</version>
</dependency>
<!-- Servlet Dependency -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!-- this is for integrating swagger -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-data-rest</artifactId>
<version>2.6.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<!-- Embedded Apache Tomcat required for testing web application -->
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<path>/</path>
</configuration>
</plugin>
</plugins>
</build>
WebConfig.java
package com.boraji.tutorial.spring.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import com.google.common.base.Predicates;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = { "com.boraji.tutorial.spring.controller" })
public class WebConfig extends WebMvcConfigurerAdapter {
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
BookController.java
package com.boraji.tutorial.spring.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.boraji.tutorial.spring.model.Book;
import com.boraji.tutorial.spring.service.BookService;
import io.swagger.annotations.Api;
#CrossOrigin(origins = "*")
#RestController
public class BookController {
#Autowired
private BookService bookService;
/*---Add new book---*/
#PostMapping("/book")
public ResponseEntity<?> save(#RequestBody Book book) {
long id = bookService.save(book);
return ResponseEntity.ok().body("New Book has been saved with ID:" + id);
}
/*---Get a book by id---*/
#GetMapping("/book/{id}")
public ResponseEntity<Book> get(#PathVariable("id") long id) {
Book book = bookService.get(id);
return ResponseEntity.ok().body(book);
}
/*---get all books---*/
#GetMapping("/book")
public ResponseEntity<List<Book>> list() {
List<Book> books = bookService.list();
return ResponseEntity.ok().body(books);
}
/*---Update a book by id---*/
#PutMapping("/book/{id}")
public ResponseEntity<?> update(#PathVariable("id") long id, #RequestBody Book book) {
bookService.update(id, book);
return ResponseEntity.ok().body("Book has been updated successfully.");
}
/*---Delete a book by id---*/
#DeleteMapping("/book/{id}")
public ResponseEntity<?> delete(#PathVariable("id") long id) {
bookService.delete(id);
return ResponseEntity.ok().body("Book has been deleted successfully.");
}
}
In the resources folder, i have db.properties file
# MySQL properties
mysql.driver=com.mysql.cj.jdbc.Driver
mysql.url=jdbc:mysql://localhost:3306/bookdb
mysql.user=root
mysql.password=root
# Hibernate properties
hibernate.show_sql=true
hibernate.hbm2ddl.auto=update
#C3P0 properties
hibernate.c3p0.min_size=5
hibernate.c3p0.max_size=20
hibernate.c3p0.acquire_increment=1
hibernate.c3p0.timeout=1800
hibernate.c3p0.max_statements=150
MyWebAppInitializer.java
package com.boraji.tutorial.spring.config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class MyWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { AppConfig.class };
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] { WebConfig.class };
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
can you please anyone help me that what is wrong in this? is there anything that i need to add?
You have not defined Docket bean and neither you have used the #EnableSwagger2
The configuration of Swagger mainly centers around the Docket bean. Swagger 2 is enabled through the #EnableSwagger2 annotation. Refer the below code.
#Configuration
#EnableSwagger2
public class SwaggerConfig {
#Bean
public Docket customImplementation() {
return new Docket(DocumentationType.SWAGGER_2).pathMapping("/data").apiInfo(apiInfo());
}
private ApiInfo apiInfo() {
return new ApiInfo("ISW ADR Application",
"ADR or is another business line within the Issuer services business group."
+ "The primary functionalities of ADR are maintained within the DR system (mainframe) "
+ "Four main functionalities that are imported : "
+" 1) Dividend Announcements"
+ " 2) Depositary Service fees"
+ " 3) DR Fees"
+ " 4) DR Gross revenue.",
"ADR V2", "Terms of service", "xyz", "License of API", "API license URL");
}
}
You have not enabled swagger using #EnableSwagger2 and also have not returned a Docket Bean. Refer this.
#Configuration
#EnableSwagger2
public class SwaggerConfig {
#Bean
public Docket demoApi() {
return new Docket(DocumentationType.SWAGGER_2).select()
.apis(RequestHandlerSelectors.basePackage("com.example.demo"))
.paths(PathSelectors.regex("/person.*")).build();
}
}

Cannot Autowire DataSource in Spring Boot Project

I am trying to build a simple Spring Boot CRUD application that also has login and signup options with spring boot security. I'm already working with a MySQL database and its working fine to persist the data for my application.
The problem is that, in trying to create my jdbcAuthentication, in my securityConfig class, it says that I cannot autowire Datasource, and that there are no beans of 'DataSource' type found (again, I have used my MySQL database successfully for this project, for a while now). It also automatically imports the javax.sql.DataSource import when I type it in, so it does recognize it.
I tried to search through similar questions, but just could not get it to work.
Here is my code:
Test2Application.java
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class Test2Application {
public static void main(String[] args) {
SpringApplication.run(Test2Application.class, args);
}
}
SecurityConfig.java
package com.example.demo;
import org.springframework.beans.factory.annotation.Autowired;
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.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.sql.DataSource;
#EnableWebSecurity
#RequestMapping("cheese")
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private DataSource dataSource;
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(dataSource)
.usersByUsernameQuery("select email as principal, password as credentials, true from user where email=?");
}
#Override
protected void configure(HttpSecurity http) throws Exception{
http
.authorizeRequests()
.antMatchers(
"/cheese/index",
"/cheese/",
"/**/webjars/**",
"/cheese/signup",
"/cheese/login",
"/cheese/account",
"/cheese/add",
"/cheese/remove",
"/cheese/success").permitAll()
.anyRequest().authenticated()
.and()
.formLogin().loginPage("/cheese/login")
.permitAll();
http.csrf().disable();
}
}
UserController.java
package com.example.demo.controllers;
import com.example.demo.models.Customer;
import com.example.demo.models.data.CustomerDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
#RequestMapping("cheese")
public class UserController {
#Autowired
private CustomerDao customerDao;
#RequestMapping(value = "login")
public String loginPage(Model model) {
model.addAttribute("title", "Login Page");
return "cheese/login";
}
#RequestMapping(value = "account")
public String accountInfo(Model model) {
model.addAttribute("title", "Account Page");
return "cheese/account";
}
#GetMapping("signup")
public String displaySignUpForm(Model model) {
model.addAttribute("title", "Sign Up");
model.addAttribute("customer", new Customer());
return "cheese/signup";
}
#PostMapping(value = "signup")
public String processSignUp(Model model, #ModelAttribute Customer customer, Errors errors) {
if (errors.hasErrors()) {
return "cheese/signup";
}
customerDao.save(customer);
return "cheese/success";
}
}
Application.Properties
spring.datasource.url=jdbc:mysql://localhost:8889/******?useSSL=false
spring.datasource.username=****
spring.datasource.password=******
spring.jpa.database=MYSQL
spring.jpa.hibernate.ddl-auto = update
spring.jpa.show-sql=false
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>test2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>test2</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</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-security</artifactId>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>webjars-locator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<addResources>true</addResources>
</configuration>
</plugin>
</plugins>
</build>
</project>
The Spring Security configuration should applied with the Configuration annotation.
Remove #RequestMapping("cheese") from SecurityConfig
The correct configuration:
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter
Had the same issue, I created a separate config class where I defined a DataSource bean
#Bean
DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setUrl("database_url");
dataSource.setUsername("username");
dataSource.setPassword("password");
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
return dataSource;
}
and in the main config file (in your case Security config) left DataSource #Autowired.
#Autowired
DataSource dataSource;
#Autowired
protected void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(dataSource);
}
And it worked. In case it is useful, I used these Gradle dependencies -
implementation 'mysql:mysql-connector-java:8.0.18'
implementation group: 'org.springframework', name: 'spring-jdbc', version: '5.3.21'
Apart from the #Configuration annotation, add #EnableAutoConfiguration which would attempt and configure code.
#Configuration
#EnableAutoConfiguration
public class SecurityConfig extends WebSecurityConfigurerAdapter
Also, rebuild your sources afterwards.

facing issue while starting spring boot using hikaricp

I have done the same, as some blogs have suggested. But still I couldn't able to solve the issue.
Environment:
spring - 4.2.5.RELEASE
spring boot - 1.3.3.RELEASE
hikariCP - 2.4.7
#Bean(name="HikariDataSource",destroyMethod = "shutdown")
public DataSource dataSource2() {
HikariConfig config = new HikariConfig();
config.setDriverClassName("oracle.jdbc.OracleDriver");
config.setJdbcUrl("");
config.setUsername("");
config.setPassword("");
config.addDataSourceProperty("cachePrepStmts", "true");
config.addDataSourceProperty("prepStmtCacheSize", "250");
config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
config.setPoolName("Hikaripool-1");
HikariDataSource ds = new HikariDataSource(config);
return ds;
}
#Bean
public JdbcTemplate getJdbcTemplate() {
return new JdbcTemplate(dataSource2());
}
Exception:
java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.jmx.export.UnableToRegisterMBeanException: Unable to register MBean [HikariDataSource (null)] with key 'dataSource'; nested exception is javax.management.InstanceAlreadyExistsException: com.zaxxer.hikari:name=dataSource,type=HikariDataSource
Caused by: javax.management.InstanceAlreadyExistsException: com.zaxxer.hikari:name=dataSource,type=HikariDataSource
Can anyone help me in resolving this issue.
The error "InstanceAlreadyExistsException: com.zaxxer.hikari:name=dataSource" means there is one more instance present for datasource. Please check your configuration.
Here is the sample code for jdbcTemplate using HikariCP, Spring Boot 1.4.0 and hsqldb. Please check the HikariCPConnTest.java below. Hope this helps.
pom.xml
<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>Spring-HikariCP</groupId>
<artifactId>com.my</artifactId>
<version>0.0.1-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.0.RELEASE</version>
<relativePath />
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
</dependency>
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>
application.properties
spring.datasource.driverClassName=org.hsqldb.jdbc.JDBCDriver
spring.datasource.url=jdbc:hsqldb:mem:testdb
spring.datasource.username=sa
spring.datasource.password=
HikariCPConn.java
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
#Component
#ConfigurationProperties
public class HikariCPConn {
#Value("${spring.datasource.driverClassName}")
private String driverClassName;
#Value("${spring.datasource.url}")
private String url;
#Value("${spring.datasource.username}")
private String user;
#Value("${spring.datasource.password}")
private String password;
#Bean
public DataSource getDataSource() {
HikariConfig hikariConfig = new HikariConfig();
hikariConfig.setUsername(user);
hikariConfig.setPassword(password);
hikariConfig.setDriverClassName(driverClassName);
hikariConfig.setJdbcUrl(url);
return new HikariDataSource(hikariConfig);
}
#Bean
public JdbcTemplate getJdbcTemplate() {
return new JdbcTemplate(getDataSource());
}
}
MySpringBootApp.java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class MySpringBootApp {
public static void main(String[] args) {
SpringApplication.run(new Object[] { MySpringBootApp.class }, args);
}
}
HikariCPConnTest.java
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.junit4.SpringRunner;
#RunWith(SpringRunner.class)
#SpringBootTest(classes = MySpringBootApp.class)
public class HikariCPConnTest {
#Autowired
HikariCPConn hkConn;
#Test
public void testInsert() {
JdbcTemplate jt = hkConn.getJdbcTemplate();
jt.execute("create table employee (id int, name varchar(20))");
jt.execute("insert into employee (id, name) values (1, 'Emp1')");
jt.execute("insert into employee (id, name) values (2, 'Emp2')");
List<Map<String, Object>> data = jt.queryForList("select * from employee");
assertEquals(2,data.size());
for (Map map : data) {
System.out.println(map);
}
}
}

Categories