How to fix this FirebaseApp name [DEFAULT] already exists! spring-boot and firebase - spring

I am trying make firebase auth and spring boot work for my app
here is my Application.java
import com.google.auth.oauth2.GoogleCredentials;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.reactive.function.client.WebClient;
import java.io.IOException;
#SpringBootApplication
#EnableScheduling
public class Application {
public static final Logger logger = LoggerFactory.getLogger("com.qmexpress");
static String FB_BASE_URL="https://qm-tracker-backend.firebaseio.com";
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
try {
FirebaseOptions options = new FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.fromStream(new ClassPathResource("/qm-tracker-backend-firebase-adminsdk-wowh8-d8b0c278a7.json").getInputStream()))
.setDatabaseUrl(FB_BASE_URL)
.build();
FirebaseApp.initializeApp(options);
} catch (IOException e) {
e.printStackTrace();
}
}
#Bean
public WebClient webClient() {
return WebClient.create();
}
}
After I run app I get this message
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.boot.maven.AbstractRunMojo$LaunchRunner.run(AbstractRunMojo.java:496)
at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.IllegalStateException: FirebaseApp name [DEFAULT] already exists!
at com.google.common.base.Preconditions.checkState(Preconditions.java:444)
at com.google.firebase.FirebaseApp.initializeApp(FirebaseApp.java:227)
at com.google.firebase.FirebaseApp.initializeApp(FirebaseApp.java:218)
at com.google.firebase.FirebaseApp.initializeApp(FirebaseApp.java:205)
at com.qmexpress.Application.main(Application.java:37)
... 6 more

Hope this can help for someone who has the same problem:
import com.google.auth.oauth2.GoogleCredentials;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.reactive.function.client.WebClient;
import java.io.IOException;
#SpringBootApplication
#EnableScheduling
public class Application {
public static final Logger logger = LoggerFactory.getLogger("com.example");
static String FB_BASE_URL="https://example.firebaseio.com";
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
try {
FirebaseOptions options = new FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.fromStream(new ClassPathResource("/serviceAccountKey.json").getInputStream()))
.setDatabaseUrl(FB_BASE_URL)
.build();
if(FirebaseApp.getApps().isEmpty()) { //<--- check with this line
FirebaseApp.initializeApp(options);
}
} catch (IOException e) {
e.printStackTrace();
}
}
#Bean
public WebClient webClient() {
return WebClient.create();
}
}
pom.xml , if you want to validate.
<?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>logistic</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>Backend-API</name>
<description>example</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-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>nz.net.ultraq.thymeleaf</groupId>
<artifactId>thymeleaf-layout-dialect</artifactId>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.10</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20160810</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.firebase</groupId>
<artifactId>firebase-admin</artifactId>
<version>6.2.0</version>
<exclusions>
<exclusion>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
</exclusion>
<exclusion>
<groupId>com.google.http-client</groupId>
<artifactId>google-http-client-jackson</artifactId>
</exclusion>
<exclusion>
<groupId>com.google.http-client</groupId>
<artifactId>google-http-client-gson</artifactId>
</exclusion>
<exclusion>
<groupId>com.google.api-client</groupId>
<artifactId>google-api-client-gson</artifactId>
</exclusion>
<exclusion>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
</exclusion>
<exclusion>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</exclusion>
<exclusion>
<groupId>com.google.auto.value</groupId>
<artifactId>auto-value</artifactId>
</exclusion>
<exclusion>
<groupId>org.threeten</groupId>
<artifactId>threetenbp</artifactId>
</exclusion>
<exclusion>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
</exclusion>
<exclusion>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-firestore</artifactId>
</exclusion>
<exclusion>
<groupId>com.google.apis</groupId>
<artifactId>google-api-services-storage</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
</exclusion>
<exclusion>
<groupId>com.google.api</groupId>
<artifactId>gax</artifactId>
</exclusion>
<exclusion>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-storage</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.google.code.findbugs</groupId>
<artifactId>jsr305</artifactId>
<version>3.0.2</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.google.api-client</groupId>
<artifactId>google-api-client-gson</artifactId>
<version>1.23.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
</project>

This config work for me
#Bean
FirebaseMessaging firebaseMessaging() throws IOException {
GoogleCredentials googleCredentials = GoogleCredentials
.fromStream(new ClassPathResource("fcm/appName-fa2db-firebase-adminsdk-zn2y1-98b7de2ad9.json").getInputStream());
FirebaseOptions firebaseOptions = FirebaseOptions
.builder()
.setCredentials(googleCredentials)
.build();
FirebaseApp app = null;
if(FirebaseApp.getApps().isEmpty()) {
app = FirebaseApp.initializeApp(firebaseOptions, "appName");
}else {
app = FirebaseApp.initializeApp(firebaseOptions);
}
return FirebaseMessaging.getInstance(app);
}

Yes the solution above is correct, this is due to the static context, for example in a spring project, this bean never throws that exception
#Configuration
public class FirestoreConfiguration {
#Value("${spring.gcp.firestore.projectid}")
private String projectId;
#Bean
public Firestore FirestoreDb() throws IOException {
// Use the application default credentials
GoogleCredentials credentials = GoogleCredentials.getApplicationDefault();
FirebaseOptions options = new FirebaseOptions.Builder()
.setCredentials(credentials)
.setProjectId(projectId)
.build();
FirebaseApp.initializeApp(options); //<-------- Here
return FirestoreClient.getFirestore();
}
}
But in another java project, I use this code and a need to validate if not exists.
public class FirestoreConfiguration {
// static method
public static Firestore FirestoreDb() throws IOException {
// Use the application default credentials
GoogleCredentials credentials = GoogleCredentials.getApplicationDefault();
FirebaseOptions options = new FirebaseOptions.Builder()
.setCredentials(credentials)
.setProjectId(Envars.getEnvar("GOOGLE_CLOUD_PROJECT"))
.build();
if(FirebaseApp.getApps().isEmpty()) { //<------- Here
FirebaseApp.initializeApp(options);
}
return FirestoreClient.getFirestore();
}
}

This exception appear because you are trying to create the [DEFAULT] FirebaseApp again, simply you can add a validation to check if it exist or not before the initialization, like this:
if(FirebaseApp.getInstance(FirebaseApp.DEFAULT_APP_NAME) != null) {
try {.... rest of your code
}
Also, it is better to add a configuration class instead of adding the code at main method.

This worked for me:
FirebaseApp app;
if (FirebaseApp.getApps().isEmpty()) {
app = FirebaseApp.initializeApp(firebaseOptions, "my-app");
} else {
app = FirebaseApp.getApps().get(0);
}

Related

#enabler2dbcrepositories is unable to find my repository

I m migrating my database management from blocking to non-blocking(asynchronious) api spring data r2dbc.but there are some problems i need to fix?
HERES WHAT I VE TRIED:
1.changing dependencies OF R2DBC AND other reactor stuffs.
2.changed springboot version of this project you can check my pom.xml below on my previous project (but i ve deleted that project due to some currupt classes) this worked well but now its not working.
3.changed springframework versions several times and i know R2DBC works with 5.2.0.RC2 only but dont know its still not working.
4.run maven clean install but nothing great happen.
below is my code .
heres my 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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.0.M6</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>GamOneY</groupId>
<artifactId>gamoney.startup</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>GamOneY</name>
<description>PUBG_PC_AUTOMATION_MACHINE</description>
<properties>
<java.version>12</java.version>
<org.springframework.version>5.2.0.RC2</org.springframework.version>
<spring-cloud.version>Hoxton.M2</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-netflix-eureka-client -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-netflix-hystrix -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.tomcat/tomcat-util -->
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-util</artifactId>
<version>9.0.26</version>
</dependency>
<!-- https://mvnrepository.com/artifact/tech.simter/simter-r2dbc-ext -->
<dependency>
<groupId>tech.simter</groupId>
<artifactId>simter-r2dbc-ext</artifactId>
<version>1.3.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.r2dbc/r2dbc-proxy -->
<dependency>
<groupId>io.r2dbc</groupId>
<artifactId>r2dbc-proxy</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/io.r2dbc/r2dbc-client -->
<dependency>
<groupId>io.r2dbc</groupId>
<artifactId>r2dbc-client</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot.experimental/spring-boot-autoconfigure-r2dbc -->
<dependency>
<groupId>org.springframework.boot.experimental</groupId>
<artifactId>spring-boot-autoconfigure-r2dbc</artifactId>
<version>0.1.0.M1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot.experimental</groupId>
<artifactId>spring-boot-actuator-autoconfigure-r2dbc</artifactId>
<version>0.1.0.M1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot.experimental/spring-boot-starter-data-r2dbc -->
<dependency>
<groupId>org.springframework.boot.experimental</groupId>
<artifactId>spring-boot-starter-data-r2dbc</artifactId>
<version>0.1.0.M1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<!-- <dependency> -->
<!-- <groupId>com.github.mirromutth</groupId> -->
<!-- <artifactId>r2dbc-mysql</artifactId> -->
<!-- <version>${degraph-check.version}</version> -->
<!-- </dependency> -->
<!-- https://mvnrepository.com/artifact/io.r2dbc/r2dbc-h2 -->
<dependency>
<groupId>io.r2dbc</groupId>
<artifactId>r2dbc-proxy</artifactId>
</dependency>
<dependency>
<groupId>io.r2dbc</groupId>
<artifactId>r2dbc-h2</artifactId>
</dependency>
<dependency>
<groupId>io.r2dbc</groupId>
<artifactId>r2dbc-pool</artifactId>
</dependency>
<dependency>
<groupId>io.r2dbc</groupId>
<artifactId>r2dbc-spi</artifactId>
</dependency>
<dependency>
<groupId>io.r2dbc</groupId>
<artifactId>r2dbc-spi-parent</artifactId>
<version>0.8.0.M8</version>
<type>pom</type>
</dependency>
<dependency>
<groupId>com.google.code.findbugs</groupId>
<artifactId>jsr305</artifactId>
<version>3.0.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.projectreactor/reactor-core -->
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-core</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/io.projectreactor/reactor-test -->
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<scope>test</scope>
</dependency>
<!-- <spring.framework.version>5.2.0.M2</spring.framework.version> -->
<dependency>
<groupId>com.stripe</groupId>
<artifactId>stripe-java</artifactId>
<version>9.12.0</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.4</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20171018</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.4</version>
</dependency>
<dependency>
<groupId>com.github.mautini</groupId>
<artifactId>pubg-java</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.github.mautini</groupId>
<artifactId>pubg-java-utils</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency><!-- https://mvnrepository.com/artifact/org.apache.tomcat/tomcat-jasper -->
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jasper</artifactId>
<version>9.0.17</version>
</dependency> <!-- ALWAYS NECCESARY IF WE WANT TO USE JSP IN SPRING BOOT -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency> <!-- ALWAYS NECCESARY IF WE WANT TO USE JSP IN SPRING BOOT -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>io.r2dbc</groupId>
<artifactId>r2dbc-postgresql</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.0.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.sun.xml.bind/jaxb-core -->
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-core</artifactId>
<version>2.2.7</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-r2dbc</artifactId>
<version>1.0.0.M2</version>
</dependency>
<!-- <dependency> -->
<!-- <groupId>io.r2dbc</groupId> -->
<!-- <artifactId>r2dbc-bom</artifactId> -->
<!-- <version>${r2dbc-releasetrain.version}</version> -->
<!-- <type>pom</type> -->
<!-- <scope>import</scope> -->
<!-- </dependency> -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.apache.derby</groupId>
<artifactId>derby</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<repositories>
<repository>
<id>snapshots-repo</id>
<url>https://oss.sonatype.org/content/repositories/snapshots</url>
<releases>
<enabled>false</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
<repository>
<id>spring-libs-snapshot</id>
<name>Spring Snapshot Repository</name>
<url>https://repo.spring.io/libs-snapshot</url>
</repository>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>io.r2dbc</groupId>
<artifactId>r2dbc-bom</artifactId>
<version>Arabba-M8</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- <dependency> -->
<!-- <groupId>com.vaadin</groupId> -->
<!-- <artifactId>vaadin-bom</artifactId> -->
<!-- <version>${vaadin.version}</version> -->
<!-- <type>pom</type> -->
<!-- <scope>import</scope> -->
<!-- </dependency> -->
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<pluginRepositories>
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
</pluginRepository>
</pluginRepositories>
</project>
Now here my springbootapplication main class
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.*;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.core.task.TaskExecutor;
//import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.data.r2dbc.repository.config.EnableR2dbcRepositories;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.view.*;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;
import CustomProperties.R2DBCProperties;
#EnableAsync //Asynchronisely running methods in seperate thread for handling concurrency by user requests
#EnableAutoConfiguration
#SpringBootApplication
#ComponentScan({"Phase3.Tournaments","Phase2.GamersDatabase","Phase4.Results","Phase5.BigGamesData.PUBG","ResultsRepositories","Phase6.ItsAllAboutMoney","Phase7.AwardsAreLove"})
#EnableTransactionManagement
#EnableScheduling
#EnableEurekaClient
#EnableR2dbcRepositories(basePackages="ResultRepositories")
#EntityScan("ResultsRepositories")
public class GamOneYApplication {
public static void main(String[] args) {
SpringApplication.run(GamOneYApplication.class, args);
System.out.println("I M STARTED");
}
#Bean(name="taskExecutor")
public TaskExecutor threadExecutor() { //BYDEFAULT SPRING WILL USE SIMPLEASYNCTASKEXECUTOR FOR RUNNY #ASYNC METHODS INSEPERATE THREAD WITH DEFAULT THREAD 1 PER REQUEST IF WE DONT PROVIDE THIS TASKEXECUTOR BEAN.
ThreadPoolTaskExecutor tps=new ThreadPoolTaskExecutor();
tps.setThreadNamePrefix("Another Thread");
tps.setCorePoolSize(10); //will bydefault create 10 threads in thread pool
tps.setQueueCapacity(100); //will hold pending tasts if threads are not available for the 11th request or access
tps.setMaxPoolSize(15); //if queue got full another 9 extra threads will be created
tps.initialize();
// tps.setThreadPriority(9);
return tps;
}
#Bean
public View jsonTemplate() {
MappingJackson2JsonView view = new MappingJackson2JsonView();
view.setPrettyPrint(true);
return view;
}
#Bean
#LoadBalanced
public RestTemplate restT() {
return new RestTemplate();
}
}
class where i m using my ReactiveCrudRepository(resultrepo1)
package Phase4.Results;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Future;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.r2dbc.core.DatabaseClient;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import Phase3.Tournaments.*;
import Phase5.BigGamesData.PUBG.PubgStorage;
import ResultsRepositories.*;
import io.r2dbc.spi.ConnectionFactory;
#Component
public class MatchDataFetcher {
#Autowired
private ResultRepo1 repo1; //H2-DATABASE
#Autowired
private ResultRepo2 repo2;
#Autowired
protected DatabaseClient dc;
#Autowired
protected ConnectionFactory conn;
public List match1(HttpSession session,Class fetch,String entityName) { //Reusable functions
// Sort sort=
// repo.findAll(sort); WE WILL FIND OUT WHATS IS SORT CLASS SHORTLY...
// Map killers=new HashMap(); we will use it later if we needed
List l=(List) dc.select().from(fetch).fetch().all().collectList().cache().block();
System.out.println("heres list baby"+l);
Iterator it_mp4=l.iterator();
int i=0;
List<Match1Result> ordered1=(List<Match1Result>) repo1.getSortedResult().collectList().block();
//List<Match2Result> ordered2=(List<Match2Result>) repo2.getSortedResult().collectList().block();//for second match
while(it_mp4.hasNext()) {
// MatchP4 mp4=(MatchP4) it.next(); //FETCHING AND IDENTIFYING JOINED PLAYER GAME RESULT OF PARTICULAR TOURNAMENTS
MatchP4 mp4=(MatchP4) it_mp4.next();
if(session.getAttribute("user").equals((String)mp4.getUsername())) { //checking of result wheatha a player has joined or not
//System.out.println("Ordered==="+ordered1.get(i).getPubgname());
System.out.println(session.getAttribute("user")+"-----"+mp4.getUsername()+"==========YES");
return ordered1;
}
else {
System.out.println("not found");
}
i++;
}
return null;
// MapResult=={avatarname1=chocoTaco, avatarname0=chocoTaco, survived0=3698.114, survived1=3698.114, kills0=34, username1=nikki, kills1=34, username0=nikki}
}
}
my resultrepo1
package ResultsRepositories;
import java.io.Serializable;
import java.util.List;
import org.springframework.data.r2dbc.repository.config.EnableR2dbcRepositories;
import org.springframework.data.r2dbc.repository.query.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.NoRepositoryBean;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.repository.reactive.ReactiveCrudRepository;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
#Repository
public interface ResultRepo1 extends ReactiveCrudRepository<Match1Result,Integer> {
#Transactional
//#Modifying(clearAutomatically=true,flushAutomatically=true)
#Query(value="UPDATE match1_result SET kills=$1,damage_dealt=$2 WHERE pubgname=$3")
public Mono<Match1Result> UpdateKills(int kills,float damage,String pubgname);
#Transactional
//#Modifying(clearAutomatically=true,flushAutomatically=true)
#Query(value="UPDATE match1_result SET kills=$1,survivetime=$2 WHERE pubgname=$3")
public int UpdateKillsMatch2(Integer kills,Double survivetime,String pubgname);
#Transactional
#Query(value="SELECT * from match1_result WHERE pubgname=$1")
public Mono<Match1Result> getLastKills(String pubgname);
//public List<T> getSortedKills();
#Transactional
#Query(value="SELECT * FROM match1_result ORDER BY kills,damagedealt DESC")
public Flux<Match1Result> getSortedResult();
}
this is my whole process.
i m using spring r2dbc second time but dont know why i m stuck here and i m sure its a dependency problem.
i ve also post this on my github account but its still open waiting there too for response.
please help me fix this.
this is the error i m getting on application startup:
***************************
APPLICATION FAILED TO START
Description:
Field repo1 in Phase4.Results.MatchDataFetcher required a bean of type 'ResultsRepositories.ResultRepo1' that could not be found.
The injection point has the following annotations:
- #org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'ResultsRepositories.ResultRepo1' in your configuration.
i m using spring r2dbc second time but dont know why i m stuck here and i m sure its a dependency problem.
please help me fix this.
Annotation #EnableR2dbcRepositories looking for repositories (interfaces) that extends ReactiveCrudRepository or R2dbcRepository interfaces. Take a look at this example.

Spring Boot WebFlux test not finding MockMvc

Problem
I'm trying to run a simple spring boot test and I'm getting errors that suggest it can't MockMvc at runtime. Documentation suggests I'm using the correct annotations and I created my pom.xml using start.spring.io. Not sure why its having issues.
Error:
No qualifying bean of type 'org.springframework.test.web.servlet.MockMvc'
TestCode
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
#RunWith(SpringRunner.class)
#SpringBootTest
#AutoConfigureMockMvc
public class MyWebApplicationTests {
#Autowired
MockMvc mockMvc;
#Test
public void Can_Do_Something() throws Exception {
mockMvc.perform(get("/hello-world")).andDo(print()).andExpect(status().isOk())
.andExpect(content().string(containsString("Hello World")));
}
}
Documentation:
I was using this doc as a reference ->
https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html#boot-features-testing-spring-boot-applications-testing-with-mock-environment
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.mywebapp</groupId>
<artifactId>webapp</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>my-webapp</name>
<description>Backend application</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.0.M1</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>10</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>javax.el</artifactId>
<version>2.2.6</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
</project>
As this Question seems to appear at the top of search lists when people are trying to test their endpoints after they've switched to Spring WebFlux, I'll add what I was able to determine here. (It should be noted that in the past I was having an incredibly hard time getting the WebTestClient to function with RestController annotated endpoints. But this code works. I think I was missing a dependency and it wasn't clear.)
MyService.java
#Service
public class MyService {
public String doSomething(String input) {
return input + " implementation";
}
}
MyController.java
#RestController
#RequestMapping(value = "/api/v1/my")
public class MyController {
#Autowired
private MyService myService;
#RequestMapping(value = "", method = RequestMethod.POST, consumes = {APPLICATION_JSON_VALUE})
public ResponseEntity<Mono<String>> processPost(#RequestBody String input)
{
String response = myService.doSomething(input);
return ResponseEntity.ok(Mono.just(response));
}
TestMyController.java
#ExtendWith(SpringExtension.class)
#WebFluxTest(MyController.class)
public class TestMyController {
#Autowired
private WebTestClient webTestClient;
#MockBean
private MyService myService;
#Test
public void testPost() throws Exception {
// Setup the Mock MyService. Note the 'mocked' vs 'implementation'
when(myService.doSomething(anyString())).thenAnswer((Answer<String>) invocation -> {
String input = invocation.getArgument(0);
return input + " mocked";
});
String response = webTestClient.post()
.uri("/api/v1/my")
.body(BodyInserters.fromObject("is"))
.accept(MediaType.APPLICATION_JSON)
.exchange()
.expectStatus().isOk()
.returnResult(String.class)
.getResponseBody()
.blockFirst();
assertThat(response).matches("is mocked");
}
}
The dependencies that can cause issues that are hard to diagnose appear to be from reactor-test. So if the WebTestClient is not working, make sure that dependency exists.
pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
<version>2.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>2.1.5.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<version>3.2.9.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<artifactId>jackson-module-kotlin</artifactId>
<groupId>com.fasterxml.jackson.module</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.4.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.truth</groupId>
<artifactId>truth</artifactId>
<version>0.45</version>
<scope>test</scope>
</dependency>
As pointed out by M. Deinum MockMvc isn't loaded for the WebFlux configuration in Spring Boot. You need to use WebTestClient instead. So replace AutoConfigureMockMvc with AutoConfigureWebTestClient and utilize the the webTestClient methods in its place.
One thing to note is that this is making actual web calls behind the scenes and will start the server. MockMVC does not start the server. What is the difference between MockMvc and WebTestClient?

Spring Boot Failure due to Transaction Management

I am currently developing an application using spring boot with cassandra as the database.
I have written a class which initializes my cassandra cluster. The problem starts as soon as I start using #Transactional in my DAO Layer Query Methods. System doesn't allow me to use them at a below error message is thrown at runtime -
An exception has occured in method getMdoBean with msg: No qualifying bean of type 'org.springframework.transaction.PlatformTransactionManager' available.
I don't understand what is going wrong. My app works fine without spring boot with no issues related to Transaction Management.
I tried adding JPA Support along with H2 Database and it resolved my problem. I did my homework and read about H2 Database and its in-memory data storage mechanism. I am failing to understand how is TransactionManagement issue is getting fixed? Is it because of H2 Database drivers which are taking care of it?
Secondly, I don't need H2 Database hence this solution does not seems to be good for me. Backend is Cassandra for my application. Any leads would be helpful. Thanks!
POM
<?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.shc.sov</groupId>
<artifactId>SOV</artifactId>
<version>4.4.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>SOV</name>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.3.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<org.springframework.version>4.1.4.RELEASE</org.springframework.version>
<jersey.version>1.14</jersey.version>
<maven.antrun.plugin.version>1.8</maven.antrun.plugin.version>
<java.version>1.8</java.version>
</properties>
<repositories>
<repository>
<id>shc-central</id>
<name>Sears Libraries</name>
<url>http://obuartifactoryvip.prod.ch3.s.com/artifactory/libs-release</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
<repository>
<id>shc-snapshots</id>
<name>Sears Snapshot Libraries</name>
<url>http://obuartifactoryvip.prod.ch3.s.com/artifactory/libs-snapshot</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>
<build>
<finalName>dpsserver</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<excludes>
<exclude>prod/*.*</exclude>
<exclude>qa/*.*</exclude>
<exclude>stress/*.*</exclude>
<exclude>dev/*.*</exclude>
<exclude>dev-spring-boot</exclude>
</excludes>
<filtering>false</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<id>config</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
<configuration>
<descriptor>config.xml</descriptor>
<attach>true</attach>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-eclipse-plugin</artifactId>
<configuration>
<!-- Always download and attach dependencies source code -->
<downloadSources>true</downloadSources>
<downloadJavadocs>false</downloadJavadocs>
<!-- Avoid type mvn eclipse:eclipse -Dwtpversion=2.0 -->
<wtpversion>2.0</wtpversion>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifestEntries>
<Class-Path>config/</Class-Path>
</manifestEntries>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>1.4.3.RELEASE</version>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<!-- Core utilities used by other modules. Define this if you use Spring
Utility APIs (org.springframework.core.*/org.springframework.util.*) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency> -->
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-jpa -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- In memory database used by spring-boot -->
<!-- <dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency> -->
<dependency>
<groupId>com.searshc.dce.persistence</groupId>
<artifactId>DcePersistence</artifactId>
<version>2.1</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-json</artifactId>
<version>${jersey.version}</version>
<exclusions>
<exclusion>
<artifactId>jaxb-impl</artifactId>
<groupId>com.sun.xml.bind</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>${jersey.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<!-- <dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.14</version>
</dependency> -->
<!-- https://mvnrepository.com/artifact/log4j/apache-log4j-extras -->
<dependency>
<groupId>log4j</groupId>
<artifactId>apache-log4j-extras</artifactId>
<version>1.2.17</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.3.2</version>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>commons-validator</groupId>
<artifactId>commons-validator</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<!-- <dependency> <groupId>javax.ws.rs</groupId> <artifactId>jsr311-api</artifactId>
<version>1.1.1</version> </dependency> -->
<dependency>
<groupId>com.sun.jersey.contribs</groupId>
<artifactId>jersey-spring</artifactId>
<version>${jersey.version}</version>
<exclusions>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</exclusion>
<exclusion>
<artifactId>spring-aop</artifactId>
<groupId>org.springframework</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.2.7-b41</version>
</dependency>
<!-- <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId>
<version>2.5</version> <scope>provided</scope> </dependency> -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>1.7.2</version>
</dependency>
<!-- Unit test level dependencies -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.5</version>
<scope>test</scope>
</dependency>
<!-- <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-all</artifactId>
<version>1.9.5</version> <scope>test</scope> </dependency> -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-cassandra</artifactId>
<version>1.4.6.RELEASE</version>
<exclusions>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- Compilation Level Dependencies -->
<dependency>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId>
<version>${maven.antrun.plugin.version}</version>
<scope>compile</scope>
</dependency>
<!-- DATASTAX -->
<dependency>
<groupId>com.datastax.cassandra</groupId>
<artifactId>cassandra-driver-core</artifactId>
<version>2.1.4</version>
</dependency>
<!-- DATASTAX -->
</dependencies>
</project>
Cassandra Configuration Class
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.data.cassandra.config.CassandraClusterFactoryBean;
import org.springframework.data.cassandra.config.CassandraSessionFactoryBean;
import org.springframework.data.cassandra.config.SchemaAction;
import org.springframework.data.cassandra.convert.CassandraConverter;
import org.springframework.data.cassandra.convert.MappingCassandraConverter;
import org.springframework.data.cassandra.core.CassandraOperations;
import org.springframework.data.cassandra.core.CassandraTemplate;
import org.springframework.data.cassandra.mapping.BasicCassandraMappingContext;
import org.springframework.data.cassandra.mapping.CassandraMappingContext;
import org.springframework.data.cassandra.repository.config.EnableCassandraRepositories;
import com.datastax.driver.core.PlainTextAuthProvider;
#Configuration
#ImportResource("application-context.xml")
#PropertySource(value = { "classpath:cassandra.properties" })
#EnableCassandraRepositories(basePackages = {"com.spring.sample"})
public class CassandraDsConfig {
#Autowired
private Environment env;
#Bean
public CassandraClusterFactoryBean configureCassandraCluster() {
CassandraClusterFactoryBean clusterFactory = new CassandraClusterFactoryBean();
clusterFactory.setContactPoints(env.getProperty("cassandra.Newcontactpoints"));
clusterFactory.setPort(Integer.parseInt(env.getProperty("cassandra.Newport")));
PlainTextAuthProvider plainTextAuthProvider = new PlainTextAuthProvider(env.getProperty("cassandra.username"),
env.getProperty("cassandra.password"));
clusterFactory.setAuthProvider(plainTextAuthProvider);
return clusterFactory;
}
#Bean
public CassandraMappingContext mappingContext() {
return new BasicCassandraMappingContext();
}
#Bean
public CassandraConverter converter() {
return new MappingCassandraConverter(mappingContext());
}
#Bean
public CassandraSessionFactoryBean session() throws Exception {
CassandraSessionFactoryBean session = new CassandraSessionFactoryBean();
session.setCluster(configureCassandraCluster().getObject());
session.setKeyspaceName(env.getProperty("cassandra.Newkeyspace"));
session.setConverter(converter());
session.setSchemaAction(SchemaAction.NONE);
return session;
}
#Primary
#Bean("cassandraNewTemplate")
public CassandraOperations cassandraNewTemplate() throws Exception {
return new CassandraTemplate(session().getObject());
}
}
Spring Boot Main Class
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.ImportResource;
import org.springframework.context.annotation.PropertySource;
//import org.springframework.context.annotation.PropertySource;
import org.springframework.boot.Banner;
/**
* #author bnarula
*
*/
#SpringBootApplication
#ImportResource("application-context.xml")
#Import(CassandraDsConfig.class)
#PropertySource("dps.properties")
#EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
#ComponentScan(basePackages = "com.shc.marketplace.ias")
public class DPSMainModule extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return configureApplication(builder);
}
public static void main(String[] args) {
configureApplication(new SpringApplicationBuilder()).run(args);
}
private static SpringApplicationBuilder configureApplication(SpringApplicationBuilder builder) {
return builder.sources(DPSMainModule.class).bannerMode(Banner.Mode.OFF);
}
}
DAO Layer Class for Caching -
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.cassandra.core.CassandraOperations;
import org.springframework.transaction.annotation.Transactional;
import com.datastax.driver.core.querybuilder.QueryBuilder;
import com.datastax.driver.core.querybuilder.Select;
import com.searshc.dce.persistence.DcePersistence.dao.beans.FreightAreaBean;
import com.searshc.dce.persistence.DcePersistence.dao.beans.FreightAreaPOJO;
import com.shc.scinventory.dps.server.dao.CacheBuilderDAO;
import com.shc.scinventory.dps.server.model.StoretoRRCPOJO;
import com.shc.scinventory.dps.server.model.ZiptoWarehousePOJO;
public class CacheBuilderDAOImpl implements CacheBuilderDAO {
private static Logger logger = Logger.getLogger(CacheBuilderDAOImpl.class);
private Map<String, String> storeToRRCMap = new HashMap<String, String>();
private Map<String, String> ziptoWarehouseMap = new HashMap<String, String>();
private Map<String, List<FreightAreaBean>> zipToFaMap = new HashMap<String, List<FreightAreaBean>>();
List<StoretoRRCPOJO> storeToRRCList = new ArrayList<StoretoRRCPOJO>();
public List<StoretoRRCPOJO> getStoreToRRCList() {
return storeToRRCList;
}
public void setStoreToRRCList(List<StoretoRRCPOJO> storeToRRCList) {
this.storeToRRCList = storeToRRCList;
for (StoretoRRCPOJO storetoRRCBean : storeToRRCList) {
storeToRRCMap.put(storetoRRCBean.getStore(), storetoRRCBean.getRrc());
}
}
#Autowired
private CassandraOperations cassandraOperations;
private String keyspace;
#Override
public void initStatements() {
logger.debug("CacheBuilderDAOImpl : Inside method init");
if (cassandraOperations == null) {
logger.error("Cassandra not available");
} else {
List<ZiptoWarehousePOJO> ziptoWarehouseList = getZiptoWarehouseMapping();
List<StoretoRRCPOJO> storetoRRCList = getStoretoRRCMapping();
for (ZiptoWarehousePOJO ziptoWarehouseBean : ziptoWarehouseList) {
ziptoWarehouseMap.put(ziptoWarehouseBean.getDestinationZip(), ziptoWarehouseBean.getDcUnit());
}
setStoreToRRCList(storetoRRCList);
refreshZipToFaMapping();
}
}
public void refreshZipToFaMapping() {
zipToFaMap = getZipToFAMapping();
}
#Transactional
public Map<String, List<FreightAreaBean>> getZipToFAMapping() {
logger.debug("Inside method getZipToFAMapping");
Map<String, List<FreightAreaBean>> result = new HashMap<String, List<FreightAreaBean>>();
try {
Select select = QueryBuilder.select().all().from("capacity", "freight_area");
List<FreightAreaPOJO> queryResult = cassandraOperations.select(select, FreightAreaPOJO.class);
for(FreightAreaPOJO faPOJO : queryResult) {
String zip = faPOJO.getGeocode_no();
if(!result.containsKey(zip)) {
result.put(zip, new LinkedList<FreightAreaBean>());
}
FreightAreaBean faBean = new FreightAreaBean();
BeanUtils.copyProperties(faPOJO, faBean);
result.get(zip).add(faBean);
}
} catch (Exception e) {
logger.error("getZipToFAMapping Error while fetch data from DB: " + e.getMessage());
e.printStackTrace();
}
logger.debug("Exiting method getZipToFAMapping");
return result;
}
public List<ZiptoWarehousePOJO> getZiptoWarehouseMapping() {
logger.debug("Inside method getZiptoWarehouseMapping");
List<ZiptoWarehousePOJO> result = null;
try {
Select select = QueryBuilder.select().all().from(getKeyspace(), "ziptowarehouse");
result = cassandraOperations.select(select, ZiptoWarehousePOJO.class);
} catch (Exception e) {
logger.error("getZiptoWarehouseMapping Error while fetch data from DB: " + e.getMessage());
}
logger.debug("Exiting method getZiptoWarehouseMapping");
return result;
}
public List<StoretoRRCPOJO> getStoretoRRCMapping() {
logger.debug("Inside method getStoretoRRCMapping");
List<StoretoRRCPOJO> result = null;
try {
Select select = QueryBuilder.select().all().from(getKeyspace(), "storetorrc");
result = cassandraOperations.select(select, StoretoRRCPOJO.class);
} catch (Exception e) {
logger.error("getStoretoRRCMapping Error while fetch data from DB: " + e.getMessage());
}
logger.debug("Exiting method getStoretoRRCMapping");
return result;
}
public String getKeyspace() {
return keyspace;
}
public void setKeyspace(String keyspace) {
this.keyspace = keyspace;
}
public Map<String, String> getStoreToRRCMap() {
return storeToRRCMap;
}
public void setStoreToRRCMap(Map<String, String> storeToRRCMap) {
this.storeToRRCMap = storeToRRCMap;
}
public Map<String, String> getZipToWarehouseMap() {
return ziptoWarehouseMap;
}
public void setZiptoWarehouseMap(Map<String, String> ziptoWarehouseMap) {
this.ziptoWarehouseMap = ziptoWarehouseMap;
}
public Map<String, List<FreightAreaBean>> getZipToFaMap() {
return zipToFaMap;
}
public void setZipToFaMap(Map<String, List<FreightAreaBean>> zipToFaMap) {
this.zipToFaMap = zipToFaMap;
}
}
If I use #Transactional in the above class at method level, it doesn't allow without adding H2 Support for JPA. It works fine after putting up below lines of code in POM.
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
I guess the reason is you excluded HibernateJpaAutoConfiguration, is there any reason to do so, otherwise I will suggest you to add it back, maybe also add #EnableTransactionManagement to your config class.

SpringBoot Application Startup Failed due to autowire JavaMailSender - version 2.0.0-snapshot

I m using Spring Boot 2.0.0.BUILD-SNAPSHOT.
I have a problem when autowiring JavaMailSender or JavaMailSenderImpl.
If i configure #Autowired for JavaMailSender, i m getting below error.
***************************
APPLICATION FAILED TO START
***************************
Description:
Field mailSender in com.hm.assetmanagment.service.MailService required a bean of type 'org.springframework.mail.javamail.JavaMailSenderImpl' that could not be found.
- Bean method 'mailSender' not loaded because #ConditionalOnClass did not find required class 'javax.mail.internet.MimeMessage'
Action:
Consider revisiting the conditions above or defining a bean of type 'org.springframework.mail.javamail.JavaMailSenderImpl' in your configuration.
Below are my pom.xml which has spring boot starter email.
<?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.hm.assetmanagement</groupId>
<artifactId>AssetManagementSystem</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>AssetManagementSystem</name>
<description>AssetManagementSystem</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.BUILD-SNAPSHOT</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</groupId>
<artifactId>spring-context-support</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-data-rest</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-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</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>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
<!-- <exclusions>
<exclusion>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
</exclusion>
</exclusions>-->
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
</project>
package com.hm.assetmanagment.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class MailService {
#Autowired
private JavaMailSenderImpl mailSender;
#RequestMapping("/assets/allocateemail/{name}/{email}/{assetid}")
private void sendAssetAllocationEmail(String name, String email, String assetid) {
/*SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
simpleMailMessage.setTo(email);
simpleMailMessage.setSubject("Asset Allocation Confirmation");
simpleMailMessage.setText("Hello " + name + "," + assetid + "\n" + " - Asset allocated to you");
mailSender.send(simpleMailMessage);*/
}
}
I tried by adding javax.mail jar/spring context support manually in dependency but it didnt work.
application.properties:
spring.mail.host=smtp.gmail.com
spring.mail.username=xxx#gmail.com
spring.mail.password=xxx
spring.mail.port=587
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console
spring.thymeleaf.cache=false
debug=true
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
Main Class:
package com.hm.assetmanagment;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
#EnableJpaRepositories
#SpringBootApplication
public class AssetManagementSystemApplication {
public static void main(String[] args) {
SpringApplication.run(AssetManagementSystemApplication.class, "--debug");
//SpringApplication.run(AssetManagementSystemApplication.class, args);
}
}
Please guide.
Update from me Nov22:
If i create new class and enable auto configuration on that class, JavaMailSender and JavaMailSenderImpl are autowired properly and spring boot application starts successfully. Already i have enableautoconfiguration in application.class as well. Is it fine to have two classes configured with enableautoconfiguration? Is there any other way to autowire JavaMailSender?
#EnableAutoConfiguration
public class MailConfig {
#Autowired
private JavaMailSenderImpl mailSender;
}
well it looks like you have not configured the Mailer at all , thus Spring cannot find the bean in order to wire it. If it was a dependency issue , then you would get a ClassNotFoundException or NoClassDefException , which is not your case.
Anyway try to configure your Mailer like this :
#Configuration
public class MailConfig {
#Bean
public JavaMailSender javaMailService() {
JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
javaMailSender.setHost("myHost");
javaMailSender.setPort(25);
javaMailSender.setJavaMailProperties(getMailProperties());
return javaMailSender;
}
private Properties getMailProperties() {
Properties properties = new Properties();
properties.setProperty("mail.transport.protocol", "smtp");
properties.setProperty("mail.smtp.auth", "false");
properties.setProperty("mail.smtp.starttls.enable", "false");
properties.setProperty("mail.debug", "false");
return properties;
}
}
Original answer here
By seeing your code , you need to add below properties to work
Sample app.yml file
spring
mail:
default-encoding: UTF-8
host: localhost
port: 8025
protocol: smtp
test-connection: false
properties.mail.smtp:
starttls.enable: true
Here is the reference
https://docs.spring.io/spring-boot/docs/2.1.x/reference/html/boot-features-email.html
make sure you are reading app properties
Change
#Autowired
private JavaMailSenderImpl mailSender;
to
#Autowired
private JavaMailSender mailSender;
The reason for this is, that by default Spring creates JDK proxies, if a bean class implements an interface. The JDK proxy implements the same interfaces as the bean class, but does not extend the class.

Spring Boot data source

I use Spring boot in my Application and trying to create a DataSource using UCP and stuck with the following error. Similar question has already been posted but interested in knowing the reason with this configuration.
Caused by: org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set
at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.determineDialect(DialectFactoryImpl.java:104)
at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.buildDialect(DialectFactoryImpl.java:71)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:205)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:111)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:234)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:206)
at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1887)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1845)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:852)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:845)
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.withTccl(ClassLoaderServiceImpl.java:398)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:844)
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:343)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:318)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1625)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1562)
... 143 more
But I have add the hibernate.dialect.
Aplication.java,
#Configuration //#EnableAutoConfiguration #ComponentScan #EnableAutoConfiguration(exclude = { DataSourceAutoConfiguration.class }) #SpringBootApplication public class DialerApplication {
public static void main(String[] args) {
SpringApplication.run(DialerApplication.class, args);
} }
DataSource file,
#Configuration
#ComponentScan
#EnableTransactionManagement
#EnableAutoConfiguration
#EnableJpaRepositories(entityManagerFactoryRef = "dialerEntityManagerFactory", transactionManagerRef = "dialerTransactionManager", basePackages = { "com.nervytech.dialer.db.repository" })
public class ApplicationDataSource {
/** The Constant LOGGER. */
private static final Logger LOGGER = LoggerFactory
.getLogger(ApplicationDataSource.class);
/** The Constant TEST_SQL. */
private static final String TEST_SQL = "select 1 from dual";
/** The pooled data source. */
private PoolDataSource pooledDataSource;
/** The environment. */
private Environment environment;
/** The Constant CONNECTION_WAIT_TIMEOUT_SECS. */
private static final int CONNECTION_WAIT_TIMEOUT_SECS = 300;
/**
* Data source.
*
* #return the pool data source
*/
#Bean(name = "dialerDataSource")
#Primary
public PoolDataSource dialerDataSource() {
this.pooledDataSource = PoolDataSourceFactory.getPoolDataSource();
final String databaseDriver = environment
.getRequiredProperty("application.datasource.driverClassName");
final String databaseUrl = environment
.getRequiredProperty("application.datasource.url");
final String databaseUsername = environment
.getRequiredProperty("application.datasource.username");
final String databasePassword = environment
.getRequiredProperty("application.datasource.password");
final String initialSize = environment
.getRequiredProperty("application.datasource.initialSize");
final String maxPoolSize = environment
.getRequiredProperty("application.datasource.maxPoolSize");
final String minPoolSize = environment
.getRequiredProperty("application.datasource.minPoolSize");
// final String poolName =
// environment.getRequiredProperty("application.datasource.poolName");
try {
pooledDataSource.setConnectionFactoryClassName(databaseDriver);
pooledDataSource.setURL(databaseUrl);
pooledDataSource.setUser(databaseUsername);
pooledDataSource.setPassword(databasePassword);
pooledDataSource.setInitialPoolSize(Integer.parseInt(initialSize));
pooledDataSource.setMaxPoolSize(Integer.parseInt(maxPoolSize));
pooledDataSource.setMinPoolSize(Integer.parseInt(minPoolSize));
pooledDataSource.setSQLForValidateConnection(TEST_SQL);
pooledDataSource.setValidateConnectionOnBorrow(Boolean.TRUE);
pooledDataSource
.setConnectionWaitTimeout(CONNECTION_WAIT_TIMEOUT_SECS);
// pooledDataSource.setConnectionPoolName(poolName);
} catch (NumberFormatException e) {
LOGGER.error("Unable to parse passed numeric value", e);
} catch (SQLException e) {
LOGGER.error("exception creating data pool", e);
}
LOGGER.info("Setting up datasource for user:{} and databaseUrl:{}",
databaseUsername, databaseUrl);
return this.pooledDataSource;
}
#Bean(name = "dialerEntityManagerFactory")
public EntityManagerFactory entityManagerFactory() {
LocalContainerEntityManagerFactoryBean lef = new LocalContainerEntityManagerFactoryBean();
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
lef.setDataSource(dialerDataSource());
lef.setJpaVendorAdapter(vendorAdapter);
lef.setPackagesToScan("com.nervytech.dialer.db.domain");
lef.setJpaProperties(additionalProperties());
lef.setPersistenceUnitName("dialerPersistenceUnit");
lef.afterPropertiesSet();
return lef.getObject();
}
#Bean(name = "dialerTransactionManager")
public PlatformTransactionManager transactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory());
return transactionManager;
}
Properties additionalProperties() {
Properties properties = new Properties();
properties.setProperty("hibernate.dialect",
"org.hibernate.dialect.MySQL5Dialect");
properties.setProperty("hibernate.show_sql","true");
return properties;
}
/**
* Sets the environment.
*
* #param environment
* the new environment
*/
#Autowired
public void setEnvironment(Environment environment) {
this.environment = environment;
}
}
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.nervytech</groupId>
<artifactId>dialer</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>dialer</name>
<description>Nervy Dialer</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.1.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<start-class>com.nervytech.dialer.DialerApplication</start-class>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</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-integration</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</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-security</artifactId>
</dependency> -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-ws</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-mail</artifactId>
<version>4.0.3.RELEASE</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<!-- <version>3.2.1</version>-->
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ucp</artifactId>
<version>11.2.0.3</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<!-- <version>5.1.6</version>-->
</dependency>
<dependency>
<groupId>javax.json</groupId>
<artifactId>javax.json-api</artifactId>
<version>1.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
Not sure why this error is still coming though the dialect is there in the dialerEntityManagerFactory.
Thanks,
Baskar.S
After further research, I found a solution and wanted to share.
Below is my property file.
application.datasource.driverClassName=com.mysql.jdbc.jdbc2.optional.MysqlDataSource
application.datasource.url=jdbc:mysql://localhost:3306/dbName
application.datasource.username=root
application.datasource.password=root
application.datasource.initialSize=5
application.datasource.maxPoolSize=5
application.datasource.minPoolSize=5
There was some empty space after the database name in the datasource.url. Spring will throw such error if the database connection is not established during the startup.
But adding the below property will let you start Spring boot though the db connection is not established.
spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.MySQL5Dialect
But Spring boot will reestablish the connection on the fly whenever the DB connection could be established after the startup.
Thanks,
Baskar.S

Resources