I have this exception when i try to start my spring boot application. I have added mysql-connector-java and spring-boot-starter-jdbc dependencies and have no idea what do not work.
Description:
Cannot determine embedded database driver class for database type NONE
Action:
If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (no profiles are currently active).
EDIT 1
This is my maven config 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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework</groupId>
<artifactId>test</artifactId>
<version>0.1.0</version>
<properties>
<java.version>1.8</java.version>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.1.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-releases</id>
<url>https://repo.spring.io/libs-release</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-releases</id>
<url>https://repo.spring.io/libs-release</url>
</pluginRepository>
</pluginRepositories>
</project>
EDIT 2
This here is data source config
public class DataSourceConfig {
#Bean
public DataSource getDataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/hcharts");
dataSource.setUsername("root");
dataSource.setPassword("root");
return dataSource;
}
#Bean
public JdbcTemplate jdbcTemplate() {
return new JdbcTemplate(getDataSource());
}
}
It looks like you are missing the #Configuration annotation on your DatasourceConfig.java file.
I tried with the annotation and mvn spring-boot:run starts up fine. Without the annotation I get the text you had indicated followed by a huge stacktrace:
APPLICATION FAILED TO START > [26/818]
Description:
Cannot determine embedded database driver class for database type NONE
Action:
If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may ne$
d to active it (no profiles are currently active).
Here is my my/DatasourceConfig.java:
package my.config;
import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import javax.sql.DataSource;
#Configuration
public class DatasourceConfig {
#Bean
public DataSource getDataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/hcharts");
dataSource.setUsername("root");
dataSource.setPassword("root");
return dataSource;
}
#Bean
public JdbcTemplate jdbcTemplate() {
return new JdbcTemplate(getDataSource());
}
}
The application will also start up, without the #Configuration, if you add a dependency to a known embedded database like hsqldb:
<dependencies>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<scope>runtime</scope>
</dependency>
...
</dependencies>
Related
My goal is to get the config for world-service from a config-service.
The architecture:
config-service with dependency spring-cloud-config-server at localhost:8888
world-service with dependency the spring-web and spring-cloud-starter-config.
What I have done:
I have set up the Config Server and send a GET request to http://localhost:8888/hello-service/master and the config server get the hello-service.properties from the config-repo repository. (If you need the config-service's source code, I will push it to this repository.)
My expected result:
The world-service use port 8081.
My actual result:
The world-service use port 8080.
bootstrap.properties
spring.application.name=world-service
spring.cloud.config.uri=http://localhost:8888
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.4.0</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>world-service</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>world-service</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>11</java.version>
<spring-cloud.version>2020.0.0-M5</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.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>
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
</repository>
</repositories>
</project>
With Spring Cloud 2020, they made a change in how bootstrap works and you have to include a new starter: spring-cloud-starter-bootstrap.
I spent a day on it and finally found a solution. It may help others
You need to add new dependency
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bootstrap</artifactId>
</dependency>
According to the Spring Cloud 2020.0
Bootstrap, provided by spring-cloud-commons, is no longer enabled by
default. If your project requires it, it can be re-enabled by
properties or by a new starter.
To re-enable by properties set spring.cloud.bootstrap.enabled=true or
spring.config.use-legacy-processing=true. These need to be set as an
environment variable, java system property or a command line argument.
The other option is to include the new spring-cloud-starter-bootstrap
(in your POM file).
I used the first option and that worked for me.
Spring Boot 2.4 introduced a new way to import configuration data via the spring.config.import property. This is now the default way to bind to Config Server.
To connect to config server set the following in application.yml:
spring:
application:
name: APPLICATION_NAME
config:
import: optional:configserver:http://USER:PASSWORD#MY_HOST:PORT/
You can see more details in: https://docs.spring.io/spring-cloud-config/docs/3.0.0/reference/html/#config-data-import
I have issue with reading the values from the application.properties file and get the following errors,
[ERROR] Failed to execute goal org.springframework.boot:spring-boot-maven-plugin:2.1.7.RELEASE:run (default-cli) on project wedding-card: An exception occurred while running. null: InvocationTargetException: Error creating bean with name 'weddingCardConfiguration': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'aws.s3.access.key' in value "${aws.s3.access.key}" -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.springframework.boot:spring-boot-maven-plugin:2.1.7.RELEASE:run (default-cli) on project wedding-card: An exception occurred while running. null
at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:215)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:156)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:148)
Caused by: org.apache.maven.plugin.MojoExecutionException: An exception occurred while running. null
at org.springframework.boot.maven.AbstractRunMojo$IsolatedThreadGroup.rethrowUncaughtException (AbstractRunMojo.java:512)
at org.springframework.boot.maven.RunMojo.runWithMavenJvm (RunMojo.java:94)
at org.springframework.boot.maven.AbstractRunMojo.run (AbstractRunMojo.java:244)
Caused by: 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:543)
at java.lang.Thread.run (Thread.java:748)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'weddingCardConfiguration': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'aws.s3.access.key' in value "${aws.s3.access.key}"
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties (AutowiredAnnotationBeanPostProcessor.java:380)
Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'aws.s3.access.key' in value "${aws.s3.access.key}"
The pom.xml file is provided:
<?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.1.7.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.wedcard</groupId>
<artifactId>wedding-card</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>wedding-card</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-data-jpa</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-mail</artifactId>
</dependency>
<dependency>
<groupId>org.liquibase</groupId>
<artifactId>liquibase-core</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.8</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.16</version>
</dependency>
<dependency>
<groupId>com.stripe</groupId>
<artifactId>stripe-java</artifactId>
<version>10.0.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk</artifactId>
<version>1.11.163</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>com.github.jhonnymertz</groupId>
<artifactId>java-wkhtmltopdf-wrapper</artifactId>
<version>1.1.11-RELEASE</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
<!-- <resources>-->
<!-- <resource>-->
<!-- <directory>resources</directory>-->
<!-- <targetPath>${project.build.outputDirectory}</targetPath>-->
<!-- <includes>-->
<!-- <include>application.properties</include>-->
<!-- </includes>-->
<!-- </resource>-->
<!-- </resources>-->
</build>
<repositories>
<repository>
<id>spring.io</id>
<url>https://repo.spring.io/plugins-release/</url>
</repository>
</repositories>
</project>
The configuration source file is here:
#Configuration
#EnableSwagger2
#EnableScheduling
//#PropertySource(value = "classpath:application.properties")
public class WeddingCardConfiguration implements WebMvcConfigurer {
// #Value("${spring.mail.host}")
// private String smtpMailHost;
// #Value("${spring.mail.port}")
// private int smtpMailPort;
// #Value("${spring.mail.username}")
// private String mailUsername;
// #Value("${spring.mail.password}")
// private String mailPassword;
#Value("${aws.s3.access.key}")
private String awsS3AccessKey;
#Value("${aws.s3.access.secret}")
private String awsS3AccessSecret;
#Value("${aws.s3.bucket.region.name}")
private String awsBucketRegionName;
#Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
}
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("*");
}
// #Bean
// public JavaMailSender javaMailSender() {
// JavaMailSenderImpl sender = new JavaMailSenderImpl();
// Properties prop = new Properties();
// prop.put("mail.smtp.auth", "true");
// prop.put("mail.smtp.starttls.enable", "true"); //TLS
// sender.setJavaMailProperties(prop);
// sender.setHost(smtpMailHost);
// sender.setPort(smtpMailPort);
// sender.setUsername(mailUsername);
// sender.setPassword(mailPassword);
//
// return sender;
// }
#Bean
public AmazonS3 awsS3Client() {
AWSCredentials credentials = new BasicAWSCredentials(awsS3AccessKey, awsS3AccessSecret);
return AmazonS3ClientBuilder
.standard()
.withCredentials(new AWSStaticCredentialsProvider(credentials))
.withRegion(awsBucketRegionName)
.build();
}
}
The project has standard file structure provided:
I have tried to provide the property source information to the configuration class but still get the same error:
#Configuration
#EnableSwagger2
#EnableScheduling
#PropertySource(value = "classpath:application.properties")
public class WeddingCardConfiguration implements WebMvcConfigurer {
}
I have also tried to provide explicitly the resources info to the pom file:
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
<resources>
<resource>
<directory>resources</directory>
<targetPath>${project.build.outputDirectory}</targetPath>
<includes>
<include>application.properties</include>
</includes>
</resource>
</resources>
</build>
I keep getting the same error. Whats the issue here and how to solve it?
ps: The email config values are commented purposefully and the error is not related to that
Check that those properties are actually defined in application.properties. There is also an application-aws.properties file, if the properties are only in that file then you will need to tell Spring Boot to enable the aws profile with SPRING_PROFILES_ACTIVE=aws, or add the aws properties with empty values in application.properties.
If no Spring Boot profile is activated, it will only use the properties defined in application.properties.
If you enable the aws profile, it will use use properties from application.properties as defaults, and then any matching properties defined in application-aws.properties will override those from application.properties if defined.
If what you are trying to do it only use those AWS properties when deployed to AWS, then you might need to make a Configuration object that holds those properties in it(which is a better practice than including properties with #Value in code), and make the AmazonS3 bean creation conditional on those properties being set.
Given that your project structure is a standard Maven structure, convention over configuration should apply and there should be no need to try and explicitly include application.properties with additional class path configuration. I.e everything under /src/main/resources should be available on the class path and to the application at runtime.
I needed to add a bean in the configuration file that would read the extra properties file,
#Bean
public PropertyPlaceholderConfigurer properties() {
final PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
// ppc.setIgnoreUnresolvablePlaceholders(true);
ppc.setIgnoreResourceNotFound(true);
final List<Resource> resourceLst = new ArrayList<Resource>();
resourceLst.add(new ClassPathResource("application.properties"));
resourceLst.add(new ClassPathResource("application-local.properties"));
ppc.setLocations(resourceLst.toArray(new Resource[]{}));
return ppc;
}
Afterwards, its working fine.
I'm completely new to Spring. and i have followed this tutorial
Currently we are using DB2 on z/OS so i tried to connect to the DB2 using the same way the tutorial used to connect to H2. however after a struggle i successfully installed the Jar files using Maven. but when i try to run this Jar i get this error
APPLICATION FAILED TO START
Description:
Parameter ٠ of constructor in
ess.nbe.dev.essentis.services.Tgen008Service required a bean of type
'ess.nbe.dev.essentis.repo.Tgen008Repository' that could not be found.
Action:
Consider defining a bean of type
'ess.nbe.dev.essentis.repo.Tgen008Repository' in your configuration.
And i think the project structure match Spring requirement disccussed here .
I followed the instructions and i couldn't figure out what is the problem ?
Here's my Code
package ess.nbe.dev.essentis.domain;
import org.springframework.context.annotation.Bean;
import javax.persistence.*;
import java.io.Serializable;
#Entity
public class Tgen008 implements Serializable {
#Id
private String ACT_IDN_SKY;
#Column
private String ACT_RFE_NBR_TXT;
public Tgen008(String ACT_IDN_SKY, String ACT_RFE_NBR_TXT) {
this.ACT_IDN_SKY = ACT_IDN_SKY;
this.ACT_RFE_NBR_TXT = ACT_RFE_NBR_TXT;
}
public Tgen008() {
}
public String getACT_IDN_SKY() {
return ACT_IDN_SKY;
}
public void setACT_IDN_SKY(String ACT_IDN_SKY) {
this.ACT_IDN_SKY = ACT_IDN_SKY;
}
public String getACT_RFE_NBR_TXT() {
return ACT_RFE_NBR_TXT;
}
public void setACT_RFE_NBR_TXT(String ACT_RFE_NBR_TXT) {
this.ACT_RFE_NBR_TXT = ACT_RFE_NBR_TXT;
}
}
And this is my Repository :
package ess.nbe.dev.essentis.repo;
import ess.nbe.dev.essentis.domain.Tgen008;
import org.springframework.data.repository.CrudRepository;
public interface Tgen008Repository extends CrudRepository<Tgen008,String> {
}
and here's my Service:
package ess.nbe.dev.essentis.services;
import ess.nbe.dev.essentis.repo.Tgen008Repository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
#Service
public class Tgen008Service {
private Tgen008Repository tgen008Repository;
#Autowired
public Tgen008Service(Tgen008Repository tgen008Repository) {
this.tgen008Repository = tgen008Repository;
}
public long total() { return tgen008Repository.count();}
}
and my MainApplication :
package ess.nbe.dev.essentis;
import ess.nbe.dev.essentis.repo.Tgen008Repository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import java.util.Arrays;
#SpringBootApplication
public class EssentisApplication {
public static void main(String[] args) {
SpringApplication.run(EssentisApplication.class, args);
}
#Bean
CommandLineRunner init(Tgen008Repository tgen008Repository) {
return args -> tgen008Repository.count();
}
}
and Application.properties :
# ===============================
# = DATA SOURCE
# ===============================
# Set here configurations for the database connection
spring.datasource.url=jdbc:db2://ipAddress:port/DBName
spring.datasource.username=username
spring.datasource.password=password
spring.jpa.properties.hibernate.default_schema=Qualifier
spring.datasource.driver-class-name=com.ibm.db2.jcc.DB2Driver
# Keep the connection alive if idle for a long time (needed in production)
spring.datasource.testWhileIdle=true
spring.datasource.validationQuery=select 1 from tgen008 fetch first row only
# Naming strategy
spring.jpa.hibernate.naming.implicit-strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyHbmImpl
spring.jpa.hibernate.naming.physical-strategy=org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy
# Allows Hibernate to generate SQL optimized for a particular DBMS
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.DB2Dialect
and 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>
<groupId>ess.nbe.dev</groupId>
<artifactId>essentis</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>essentis</name>
<description>Program for Essentis DB</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.4.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>
<repositories>
<repository>
<id>com.ibm.db2.jcc</id>
<releases>
<enabled>true</enabled>
<checksumPolicy>ignore</checksumPolicy>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
<url>file://${project.basedir}/lib/</url>
</repository>
</repositories>
<dependencies>
<!-- <dependency>
<groupId>com.ibm.db2.jcc</groupId>
<artifactId>db2jcc</artifactId>
<version>10.1</version>
</dependency>-->
<dependency>
<groupId>com.ibm.db2.jcc</groupId>
<artifactId>db2jcc_license_cisuz</artifactId>
<version>10.1</version>
</dependency>
<dependency>
<groupId>com.ibm.db2.jcc</groupId>
<artifactId>db2java</artifactId>
<version>10.1</version>
</dependency>
<dependency>
<groupId>com.ibm.db2.jcc</groupId>
<artifactId>db2jcc_javax</artifactId>
<version>10.1</version>
</dependency>
<dependency>
<groupId>com.ibm.db2.jcc</groupId>
<artifactId>db2jcc4</artifactId>
<version>10.1</version>
</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-jersey</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-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Change your service in:
#Service
public class Tgen008Service {
#Autowired
private Tgen008Repository tgen008Repository;
public long total() { return tgen008Repository.count();}
}
I figured out what was the problem, i had 2 jar files db2jcc.jar , and db2jcc4.jar.
both were in my repository, it seems that the program was using the db2jcc.jar instead of db2jcc4.jar although i didnt add it in pom.xml .
so deleting the db2jcc.jar from the local repository solved the problem.
more details about the difference between both Jars can be found in this link
package ess.nbe.dev.essentis.repo;
import ess.nbe.dev.essentis.domain.Tgen008;
import org.springframework.data.repository.CrudRepository;
#Repository // Need to add this
public interface Tgen008Repository extends CrudRepository<Tgen008, String> {
}
I am new to Spring and Spring Boot. I am trying to connect to a Postgresql database in my Spring Boot app.
I've tried to take inspiration from
http://spring.io/guides/gs/accessing-data-mysql/
and
https://docs.spring.io/spring-boot/docs/current/reference/html/howto-data-access.html
Basically I have an application.properties file that contains:
app.datasource.url=jdbc:postgresql://localhost:5432/db_example
app.datasource.username=myusername
app.datasource.password=mypassword
app.datasource.driver-class-name=org.postgresql.Driver
Using the psql tool I can normally connect to the db_example database on localhost with the 5432 port and those username and password.
Then I have a MyConfig.java which contains:
package hello;
import javax.sql.DataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
#Configuration
public class MyConfig {
#Bean
#Primary
#ConfigurationProperties(prefix = "app.datasource")
public DataSource dataSource() {
DataSourceBuilder dsb = DataSourceBuilder.create();
if (dsb == null) {
return null;
}
return dsb.build();
}
}
Then in MainController.java one of the methods that has a #GetMapping annotation, I call the dataSource() method. On the returned object I call getConnection() but that throws an SQLException with message The url cannot be null.
Also in the console the Spring Boot app writes several things:
Not loading a JDBC driver as driverClassName property is null.
and
Unable to create initial connections of pool
What am I missing? I guess some annotation in MyConfig.java?
EDIT: You might also want to see my pom.xml used to package the thing with mvn:
<?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>org.springframework</groupId>
<artifactId>gs-mysql-data</artifactId>
<version>0.1.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.8.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- JPA Data (We are going to use Repositories, Entities, Hibernate, etc...) -->
<!--<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>-->
<!-- Use MySQL Connector-J -->
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<java.version>1.8</java.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
It seems DataSourceBuilder is not set the properties. Can you try to use the default config in Spring like:
spring.datasource.url=jdbc:postgresql://localhost:5432/db_example
spring.datasource.username=myusername
spring.datasource.password=mypassword
spring.datasource.driver-class-name=org.postgresql.Driver
More detail in here: https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-sql.html
Then in your code, you have to get these properties and set them:
#Value("${spring.datasource.url}")
private String url;
#Value("${spring.datasource.username}")
private String username;
#Value("${spring.datasource.password}")
private String password;
#Value("${spring.datasource.driver-class-name}")
private String driver;
DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
dataSourceBuilder.driverClassName(driver);
dataSourceBuilder.username(username);
dataSourceBuilder.password(password);
dataSourceBuilder.url(url)
Hope this help.
This question already has answers here:
Spring boot Security Disable security
(24 answers)
Closed 2 years ago.
I have a spring boot web app with spring security configured. I want to disable authentication for a while (until needed).
I add this to the application.properties:
security.basic.enable: false
management.security.enabled: false
Here is some part of my
But I still have a basic security included : There is a default security password generated at startup and I am still getting HTTP Authentication prompt box.
My 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>fr.test.sample</groupId>
<artifactId>navigo</artifactId>
<version>1.0.0-SNAPSHOT</version>
<!-- Inherit defaults from Spring Boot -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.1.RELEASE</version>
</parent>
<properties>
<java.version>1.7</java.version>
<jsoup.version>1.8.3</jsoup.version>
<guava.version>18.0</guava.version>
<postgresql.version>9.3-1103-jdbc41</postgresql.version>
</properties>
<!-- Add typical dependencies for a web application -->
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</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-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>${jsoup.version}</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>
</dependencies>
<!-- Package as an executable jar -->
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<!-- Add Spring repositories -->
<!-- (you don't need this if you are using a .RELEASE version) -->
<repositories>
<repository>
<id>spring-snapshots</id>
<url>http://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>spring-milestones</id>
<url>http://repo.spring.io/milestone</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<url>http://repo.spring.io/snapshot</url>
</pluginRepository>
<pluginRepository>
<id>spring-milestones</id>
<url>http://repo.spring.io/milestone</url>
</pluginRepository>
</pluginRepositories>
</project>
The security is configured in WebSecurityConfig.java (I have commented the annotation to disable it) :
//#Configuration
//#EnableWebSecurity
//#EnableGlobalMethodSecurity(prePostEnabled = true)
//#Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
UserDetailsService userDetailsService;
#Autowired
UserService userService;
#Autowired
private DataSource datasource;
#Override
protected void configure(HttpSecurity http) throws Exception {
// http.authorizeRequests().antMatchers("/bus/topologie", "/home")
// http.authorizeRequests().anyRequest().authenticated()
// .antMatchers("/admin/**").access("hasRole('ADMIN')").and()
// .formLogin().failureUrl("/login?error")
// .defaultSuccessUrl("/bus/topologie").loginPage("/login")
// .permitAll().and().logout()
// .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
// .logoutSuccessUrl("/login").permitAll().and().rememberMe()
// .rememberMeParameter("remember-me")
// .tokenRepository(persistentTokenRepository())
// .tokenValiditySeconds(86400).and().csrf();
}
#Bean
public PersistentTokenRepository persistentTokenRepository() {
JdbcTokenRepositoryImpl tokenRepositoryImpl = new JdbcTokenRepositoryImpl();
tokenRepositoryImpl.setDataSource(datasource);
return tokenRepositoryImpl;
}
#Override
protected void configure(AuthenticationManagerBuilder auth)
throws Exception {
PasswordEncoder encoder = new BCryptPasswordEncoder();
auth.userDetailsService(userDetailsService).passwordEncoder(encoder);
auth.jdbcAuthentication().dataSource(datasource);
if (!userService.userExists("user")) {
User userAdmin = new User("user", encoder.encode("password"), true);
Set<Authorities> authorities = new HashSet<Authorities>();
authorities.add(new Authorities(userAdmin,"ADMIN"));
authorities.add(new Authorities(userAdmin,"CRIP"));
authorities.add(new Authorities(userAdmin,"USER"));
userAdmin.setAuthorities(authorities);
userService.createUser(userAdmin);
}
}
}
Use security.ignored property:
security.ignored=/**
security.basic.enable: false will just disable some part of the security auto-configurations but your WebSecurityConfig still will be registered.
There is a default security password generated at startup
Try to Autowired the AuthenticationManagerBuilder:
#Override
#Autowired
protected void configure(AuthenticationManagerBuilder auth) throws Exception { ... }
Try this. Make a new class
#Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.authorizeRequests().antMatchers("/").permitAll();
}
}
Basically this tells Spring to allow access to every url. #Configuration tells spring it's a configuration class
security.ignored is deprecated since Spring Boot 2.
For me simply extend the Annotation of your Application class did the Trick:
#SpringBootApplication(exclude = SecurityAutoConfiguration.class)
With this solution you can fully enable/disable the security by activating a specific profile by command line. I defined the profile in a file application-nosecurity.yaml
spring:
autoconfigure:
exclude: org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration
Then I modified my custom WebSecurityConfigurerAdapter by adding the #Profile("!nosecurity") as follows:
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
#Profile("!nosecurity")
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {...}
To fully disable the security it's enough to start the application up by specifying the nosecurity profile, i.e.:
java -jar target/myApp.jar --spring.profiles.active=nosecurity
I think you must also remove security auto config from your #SpringBootApplication annotated class:
#EnableAutoConfiguration(exclude = {
org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration.class,
org.springframework.boot.actuate.autoconfigure.ManagementSecurityAutoConfiguration.class})
Since security.disable option is banned from usage there is still a way to achieve it from pure config without touching any class flies (for me it creates convenience with environments manipulation and possibility to activate it with ENV variable) if you use Boot
spring.autoconfigure.exclude: org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration
For me only excluding the following classes worked:
import org.springframework.boot.actuate.autoconfigure.security.servlet.ManagementWebSecurityAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
#SpringBootApplication(exclude = {SecurityAutoConfiguration.class, ManagementWebSecurityAutoConfiguration.class}) {
// ...
}
This was the only thing that worked for me, I added the following annotation to my Application class and exclude SecurityAutoConfiguration
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
#EnableAutoConfiguration(exclude = {
SecurityAutoConfiguration.class
})
just add
#SpringBootApplication(exclude = SecurityAutoConfiguration.class)
You could just comment the maven dependency for a while:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<!-- <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>-->
</dependencies>
It worked fine for me
Disabling it from application.properties is deprecated for Spring Boot
2.0
Change WebSecurityConfig.java: comment out everything in the configure method and add
http.authorizeRequests().antMatchers("/**").permitAll();
This will allow any request to hit every URL without any authentication.
Use #profile("whatever-name-profile-to-activate-if-needed") on your security configuration class that extends WebSecurityConfigurerAdapter
security.ignored=/**
security.basic.enable: false
NB. I need to debug to know why why exclude auto configuration did not work for me. But the profile is sot so bad as you can still re-activate it via configuration properties if needed
Just add the following line to disable spring auto configuration in application.properties file
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration
it works on spring 2.0.5 :)
The accepted answer didn't work for me.
If you have a multi configuration, adding the following to your WebSecurityConfig class worked for me (ensure that your Order(1) is lower than all of your other Order annotations in the class):
/* UNCOMMENT TO DISABLE SPRING SECURITY */
/*#Configuration
#Order(1)
public static class DisableSecurityConfigurationAdapater extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.antMatcher("/**").authorizeRequests().anyRequest().permitAll();
}
}*/