I am using the H2 database in a Spring boot application. But unable to open it in the browser at http://localhost:8080/console. My pom.xml is as below:
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.192</version>
</dependency>
Spring boot Configuration :
Springboot configuration file
#Configuration
public class WebConfiguration {
#Bean
ServletRegistrationBean h2servletRegistration(){
ServletRegistrationBean registrationBean = new ServletRegistrationBean( new WebServlet());
registrationBean.addUrlMappings("/console/*");
return registrationBean;
}
}
to use the H2 console you need to configure it in your .properties file
spring.h2.console.enabled=true
spring.h2.console.path=/h2console/
where /h2console/ is the path you want to use on the browser so you can change it to anything. Also if you have security enabled you might want to add it to the permitted paths
also add this to your HttpSecurity configuration http.headers().frameOptions().disable();
Edit
change your security configuration i'm pretty sure you might have spring security in your pom so use this instead, if not it should work
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
#Configuration
public class WebConfiguration extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.authorizeRequests().antMatchers("/").permitAll().and()
.authorizeRequests().antMatchers("/console/**").permitAll();
httpSecurity.csrf().disable();
httpSecurity.headers().frameOptions().disable();
}
}
If have included spring-boot-starter-security artifact in your pom then by default basic authentication is enabled. Hence, to access your console either you disable the basic authentication by adding security.basic.enabled=false in your application.properties or allow the access in your configure method as below:
#Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.csrf().disable().authorizeRequests().antMatchers("/").permitAll().and().authorizeRequests()
.antMatchers("/console/**").permitAll();
httpSecurity.headers().frameOptions().disable();
}
}
Thank you all for your generous help.The application class (Springboot) was in a separate package and it was not scanning other packages.Also I modified my Pom.xml a bit which finally helped me to access the console.Attached is my new 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.spring.app</groupId>
<artifactId>Demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>SpringBootApp</name>
<description>Generator of statistics </description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.4.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<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-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--WebJars -->
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>3.3.4</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>2.1.4</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- Spring AOP + AspectJ -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
</dependency>
<!-- JavaConfig need this library -->
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>
<!-- Jackson JSON Mapper -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.7.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
go the POM file and add the dependency :
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
rebuild your project
this might help folks , all the configuration above is correct
Note - if you are not using any security then adding spring security is not required
Actualy problem is - when you open this url in chrome
http://localhost:8080/h2 chrome makes it --> https://localhost:8080/h2
To get rid of this issue - Below reference will help -
Google Chrome redirecting localhost to https
You might have face 2 situation including following errors:
localhost refused to connect
Double check the URL. Chrome automatically try to change http:// to https://
Check spring.h2.console.path (Path at witch the console avilible) to get your URL:
Default: /h2-console --> URL: http://localhost:8080/h2-console/
If you running IDE (e.g. IntelliJ Idea), make sure your app is running witch means your H2 data base is running!
You face 404 Error:
In this case your H2 Data base is correctly running on Port 8080 and you already have the connection with it.
Check spring.h2.console.path (Path at witch the console avilible) to get your URL:
Default: /h2-console --> URL: http://localhost:8080/h2-console/
Enable H2 Console
spring.h2.console.enabled=true
The issue might be also be caused by adding server.servlet.context-path to properties. The new url will be composed of server.servlet.context-path plus spring.h2.console.path
If you have renamed the h2 path in the application.properties to "console" you've to add it in your antMatcher like .antMatcher("/console/**") with two asterisks after the "console" because there are much more appendings.
If none of the above solution works, try below one, this worked for me :
Add below property in your application.propertiesfollowing
spring.data.jpa.repositories.bootstrap-mode=default
Open console in browser using this URL : http://localhost:8080/h2-console
On a login page make sure that you use jdbc:h2:mem:testdb as JDBC URL.
As h2 database console is mapped to "h2-console".
Use this:
http.csrf().disable().authorizeRequests()
.antMatchers("/h2-console/**").permitAll()
.anyRequest().authenticated();
// disable frame options
http.headers().frameOptions().disable();
`
You don't need permit root access:
.antMatchers("/") * NOT NEEDED *
Related
so I have a simple Spring Boot REST API that works fine, now I have added some swagger dependencies, both for ui and core, and have done some testing with some tags like #ApiIgnore or #Operation and they both work fine and both are updated in the http://localhost:8080/swagger-ui/#/
Now I am trying to update the API info through the #OpenAPIDefinition tag, something like this in my application class:
#OpenAPIDefinition(
info = #Info(
title = "the title",
version = "0.0",
description = "My API",
license = #License(name = "Apache 2.0", url = "http://foo.bar"),
contact = #Contact(url = "http://gigantic-server.com", name = "Fred", email = "Fred#gigagantic-server.com")))
Now I have read here that the spring boot app should do a class scan and recognize the #OpenAPIDefinition bean and update the generated json in http://localhost:8080/v3/api-docs. But this is not the case, I have also tried setting that info with openapi.yaml files but also no luck.
I suspect this might have to do with my dependencies, as I am new to swagger and still a bit lost and might have mixed something up, I leave my pom.xml here:
<?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.5.4</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb-reactive</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</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>de.flapdoodle.embed</groupId>
<artifactId>de.flapdoodle.embed.mongo</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>io.swagger.core.v3</groupId>
<artifactId>swagger-jaxrs2</artifactId>
<version>2.1.2</version>
</dependency>
<dependency>
<groupId>io.swagger.core.v3</groupId>
<artifactId>swagger-jaxrs2-servlet-initializer-v2</artifactId>
<version>2.1.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
I am at a bit of a loss on how to continue and don't understand how swagger can recognize the #ApiIgnore tag for example but ignore the #OpenAPIDefinition one. As I said I am new to this whole thing and stackoverflow in general, so please forgive me if I forgot to add any relevant code, thank you!
Try removing some unnecessary dependencies:
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>io.swagger.core.v3</groupId>
<artifactId>swagger-jaxrs2</artifactId>
<version>2.1.2</version>
</dependency>
<dependency>
<groupId>io.swagger.core.v3</groupId>
<artifactId>swagger-jaxrs2-servlet-initializer-v2</artifactId>
<version>2.1.2</version>
</dependency>
springfox-boot-starter should bring them in already.
If this does not work you can always do the following:
#Configuration
public class SwaggerConfiguration {
#Bean
public OpenAPI openAPI() {
return new OpenAPI()
.info(new Info().title("the title").version("0.0").description("My API")
.contact(new Contact().name("Fred").url("http://gigantic-server.com").email("Fred#gigagantic-server.com")));
}
}
So after a lot of different things I found this guide where it explains how to alter API info, in a nutshell, I added a #Api(tags = "Employee") to my EmployeeController class, then in my Application class added:
#Bean
public Docket docket() {
return new Docket(DocumentationType.OAS_30)
.apiInfo(new ApiInfoBuilder()
.title("Employee API")
.description("A CRUD API to demonstrate Springfox 3 integration")
.version("0.0.1-SNAPSHOT")
.license("MIT")
.licenseUrl("https://opensource.org/licenses/MIT")
.build())
.tags(new Tag("Employee", "Endpoints for CRUD operations on employees"))
.select().apis(RequestHandlerSelectors.withClassAnnotation(RestController.class))
.build();
}
And this appears to solve the issue, I now wonder what would happen if I had multiple controllers, I hope this helps anyone that was in my predicament, the overall issue seemed to be that this is a springfox related way of altering API documentation and the previous ways are swagger-core related? As I said I am new to this world so if anyone could point me out to why it wasn't working it would be amazing, thanks!
I created an app using https://start.spring.io/ so when I run ./mvnw spring-boot:run the apps work great. But then in order to be able to debug my app (as I always did with others) I select "Debug On Server" and the server compile successfully with the message INFORMACIÓN: Server startup in 4288 ms
But when I try to access to the app I get 404 error.
This is 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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.domain.app</groupId>
<artifactId>app</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>app</name>
<description>app</description>
<properties>
<java.version>1.8</java.version>
</properties>
<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-jpa</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-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Thhis is my controller:
#RestController
#RequestMapping(
value = "/api/products",
consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE
)
public class ProductController {
#Autowired
ProductService productService;
#GetMapping("")
#ResponseStatus(HttpStatus.OK)
public String getAllProducts() {
return this.productService.initCrawler();
}
}
And the URL I'm pointing is:
http://localhost:8080/app/api/products
And the response is HTTP 404
Also eclipse after the build open the explorer in http://localhost:8080/app but it gets also 404.
When running directly with ./mvnw spring-boot:run the URL that works fine is http://localhost:8080/api/products which is not working neither when I use Run as Server
And in the logs doesn't say anything...
I understood your question this way. You have created a spring boot application from Spring Initializr and the application run successfully from command line but not when you are trying to deployed in server and start the server in debug mode.
You should know that Spring Initializr created a spring boot application which is stand-alone, production-grade Spring based Applications that you can "just run". With stand-alone meaning the the server is incorporated as dependency in spring boot app and you don't need to deployed in server.
If you want to deploy in server , you need to make Spring Boot Application #SpringBootApplication class extend the SpringBootServletInitializer class.
#SpringBootApplication
public class DemoApplication extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(DemoApplication.class);
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
You should specify in maven the main class that is going to run and change the packaging from jar to war.
<packaging>war</packaging>
<start-class>com.tutorialspoint.demo.DemoApplication</start-class>
For more information how to make you spring boot application to be deployed in server, check the link : https://www.tutorialspoint.com/spring_boot/spring_boot_tomcat_deployment.htm
If you don't need the application to run on the server , you just want to debug the code. I would suggest to use eclipse or intellij. You include spring boot dashboard in perspective and start the spring boot application in debug mode. Check this link to understand how to include and use spring boot dashboard : https://medium.com/danielpadua/java-spring-boot-eclipse-744454468670
I get the following error trying to start my Spring application
ERROR 5908 --- [ main] com.zaxxer.hikari.HikariConfig : HikariPool-1 - dataSource or dataSourceClassName or jdbcUrl is required.
My application.properties file looks like this:
spring.datasource.one.jdbc-url = jdbc:postgresql://10.x.x.x:y/sampledb1
spring.datasource.one.username = someuser
spring.datasource.one.password = somepasswd
spring.datasource.one.driver-class-name = org.postgresql.Driver
spring.datasource.two.jdbc-url = jdbc:postgresql://10.x.x.x:z/sampledb2
spring.datasource.two.username = someuser
spring.datasource.two.password = somepassword
spring.datasource.two.driver-class-name = org.postgresql.Driver
And I am using DataSourceBuilder class as below:
#Configuration
public class DataSourceConfig
{
#Bean(name = "one")
#Primary
#ConfigurationProperties(prefix = "spring.datasource.one")
public DataSource dataSource1()
{
return DataSourceBuilder.create().build();
}
#Bean(name = "two")
#ConfigurationProperties(prefix = "spring.datasource.two")
public DataSource dataSource2()
{
return DataSourceBuilder.create().build();
}
}
My pom looks like this.
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.4.RELEASE</version>
<relativePath />
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
<avro.version>1.8.2</avro.version>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<version.powermock>1.6.2</version.powermock>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<artifactId>log4j-over-slf4j</artifactId>
<groupId>org.slf4j</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- actuator -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!-- eureka -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<!-- hystrix -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
</dependencies>
This was working fine earlier, but now causing some issues. And the error occurs intermittently, sometime it starts without error, other times it fails with the error.
I tried solutions suggested in the link .They don't seem to work for me.
Change jdbc-url to jdbcUrl so Hikari can find suitable driver per url.
jdbcUrl
This property directs HikariCP to use "DriverManager-based" configuration. We feel that DataSource-based configuration (above) is superior for a variety of reasons (see below), but for many deployments there is little significant difference. When using this property with "old" drivers, you may also need to set the driverClassName property, but try it first without. Note that if this property is used, you may still use DataSource properties to configure your driver and is in fact recommended over driver parameters specified in the URL itself. Default: none
This error can occur when spring looks for the properties file at the wrong location. For example, when the Java option -Dspring.config.location=... is passed to your application server at startup then your properties file of your deployed application is ignored - even if there is no properties file at spring.config.location, too.
I am trying to run my Spring Boot backend with two profiles, one using H2 in memory database and the second one using MySQL. H2 database works just fine, but when I switch to MySQL I get
APPLICATION FAILED TO START
***************************
Description:
Failed to bind properties under '' to com.zaxxer.hikari.HikariDataSource:
Property: driverclassname
Value: com.mysql.jdbc.Driver;
Origin: "driverClassName" from property source "source"
Reason: Failed to load driver class com.mysql.jdbc.Driver; in either of HikariConfig class loader or Thread context classloader
Action:
Update your application's configuration
I have tried deleting .m2, reimporting, maven clean, compile, install and most of the things I could find on the internet, no success. The funny thing is that I have other project with MySQL database only, I had similar issue, but adding mysql-connector-java dependency solved it. I have no clue right now.
application.properties
spring.profiles.active=#profilename#
#H2 in memory database
domain.datasource.type=H2
domain.datasource.url=jdbc:h2:mem:store;MODE=MYSQL;
domain.datasource.driver-class=org.h2.Driver
domain.datasource.username=sa
domain.datasource.password=
domain.datasource.generate-dll=true
application-local_mysql.properties
spring.profiles.active=#profilename#
#MySQL local database
domain.datasource.type=MYSQL
domain.datasource.url=jdbc:mysql://localhost:3600/store;
domain.datasource.driver-class=com.mysql.jdbc.Driver;
domain.datasource.username=store
domain.datasource.password=store
domain.datasource.generate-dll=false
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>sk.personal</groupId>
<artifactId>my-project</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>my-project</name>
<description>My personal project.</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.5.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</artifactId>
<version>2.0.5.RELEASE</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-web</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
<profiles>
<profile>
<id>local_h2</id>
<properties>
<profilename>local_h2</profilename>
</properties>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<id>local_mysql</id>
<properties>
<profilename>local_mysql</profilename>
<maven.test.skip>true</maven.test.skip>
</properties>
</profile>
</profiles>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
DatasourceConfig.java
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
import javax.sql.DataSource;
#Configuration
public class DatasourceConfig {
#Value("${domain.datasource.url}")
private String url;
#Value("${domain.datasource.username}")
private String username;
#Value("${domain.datasource.password}")
private String password;
#Value("${domain.datasource.type}")
private String type;
#Value("${domain.datasource.driver-class}")
private String driverClass;
#Bean
public DataSource dataSource() {
if (type.equals("MYSQL")) {
return DataSourceBuilder
.create()
.username(username)
.password(password)
.url(url)
.driverClassName(driverClass)
.build();
} else {
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
return builder
.setType(EmbeddedDatabaseType.H2)
.build();
}
}
}
In my case the next dependency was missing:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
In case of using IntelliJ and if you inherit from a <parent>, you can view your effective pom.xml by right clicking anywhere inside your pom.xml, then:
and search for the mysql-connector-java artifact as mentioned.
The answer is so embarrassing. I appended the driver line of application.properties with a semicolon ...
Obviously, it did't recognize that driver.
I had a problem where I was using Spring Boot 2.2.0.RELEASE and needed to connect to an old Mysql DB (5.1.73), which required me to downgrade to mysql-connector-java version 5.1.38
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
Since Spring boot was expecting a newer mysql-java-connector, which has been renamed to com.mysql.cj.jdbc.Driver, I also had to add the spring datasource driver-class-name setting in my spring boot db config.
So my spring boot config ended up like this:
spring:
datasource:
url: 'localhost'
password: password
username: user
driver-class-name: com.mysql.jdbc.Driver
just add mysql and jdbc dependencies like below
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>
You don't specify version of MYSQL JDBC driver, so you're likely getting version 8.x, where the driver is named differently than in previous versions:
com.mysql.cj.jdbc.Driver
In my case error throws:
Property: driverclassname
Value: com.mysql.cj.jdbc.Driver
Origin: "driverClassName" from property source "source"
Reason: Failed to load driver class com.mysql.cj.jdbc.Driver in either of HikariConfig class loader or Thread context classloader
So I have just added mysql dependency:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
Try upgrading your driver. Coz Mysql community has updated class name from com.mysql.jdbc.Driver to com.mysql.cj.jdbc. Check More Details
Change the database driver dependency scope to 'runtime'
For example:
<dependency>
<groupId>com.{yourDatabaseGroupid}</groupId>
<artifactId>{yourDatabaseArtifactId}</artifactId>
<scope>runtime</scope>
</dependency>
You should add: spring.datasource.driver-class-name=com.mysql.jdbc.Driver to your application.properties file .
My **application.properties : **
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
spring.datasource.url=jdbc:mysql://localhost:3306/db_name?useSSL=false&useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC&zeroDateTimeBehavior=convertToNull
spring.datasource.username=root
I cant believe it!
In intellij: Build->rebuild project solved the issue for me!
For more information:
pom.xml:
application.properties:
this issue for me was also caused by the version of mysql.
all i had to do is add the version of mysql in pom.xml dependencies
(in my case the verion is 8.0.25)
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.25</version>
</dependency>
make sure to reload the maven dependecies before your run
I had the same problem as you. For me, it was because of having h2 database dependency!
I don't know how these two can affect each other, but all I did was removing this dependency and now it works just fine!
I my case all configurations were correct but I still get this error.
In Intellij, go in the project structure (ctrl + alt + maj + S) in windows.
Look if u get some problems.
If yes, go on maven in the sidebar: clic on "Generate sources and Update Folders for All projetct"
That resolve my error !
Had to specify the jar path inside project->Properties->JPA-> connection Profile -> JAR List
I had the same issue and the root cause was [ spring.profile.active ]
and the fix is [ spring.profiles.active ] where it is profiles plural
and it was my mistake.
go to https://start.spring.io
In that site:
Dependencies > Search for Mysql drver > select it > Click explore button > copy the latest version of mysql connector > add it into your application.properties file
I have been fighting with getting resources to work for quite sometime now, and I know there are thousands of similar questions.. Anyway, my condition is this
I will start with my pom.. I might have missed something here?
<?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.ruruapps</groupId>
<artifactId>spring-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>spring-demo</name>
<description>Spring-Demo Application</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<org.thymeleaf-version>2.1.4</org.thymeleaf-version>
<webjars-bootstrap.version>3.3.5</webjars-bootstrap.version>
<webjars-jquery-ui.version>2.1.1</webjars-jquery-ui.version>
<webjars-jquery.version>2.0.3-1</webjars-jquery.version>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-batch</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-undertow</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-security</artifactId>
</dependency>
<!-- Thymeleaf -->
<!--<dependency>-->
<!--<groupId>org.thymeleaf</groupId>-->
<!--<artifactId>thymeleaf</artifactId>-->
<!--<version>2.1.4.RELEASE</version>-->
<!--</dependency>-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- Webjars (static dependencies distributed as WAR files) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</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>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>3.3.5</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>2.1.4</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Here are the errors I am dealing with
And in the terminal I see this
Looking up handler method for path /css/bootstrap/css/bootstrap.min.css
Did not find handler method for [/css/bootstrap/css/bootstrap.min.css]
Request method 'GET' not supported
What does this mean?
I have a correct structure and doing it by the convention
But no luck what so ever. I tried changing to public/ and tried using webjars. All in vain. What are the norms for this and how do I get this set up so it wont be breaking! Thanks!
EDIT:: Configuration Files
Here is my application file that is provided with the spring boot
#SpringBootApplication
#EnableAutoConfiguration(exclude = {
org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration.class,
org.springframework.boot.actuate.autoconfigure.ManagementSecurityAutoConfiguration.class})
#ComponentScan(basePackages = {"webapp"})
#EnableJpaRepositories
public class SpringDemoApplication {
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(SpringDemoApplication.class, args);
}
}
And I have a WebConfig file which is mostly empty, but I tried adding the #Overide on addResourceHandlers, with no improvements
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = {"webapp"})
public class WebConfig extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("classpath:/resources/static/").setCachePeriod(31556926);
}
}
EDIT
After further examining the application, I have found this
It says that the request it allows is PUT, but why? From what I can understand is that something is blocking my request to the resource files, is that right?
Desperate to get this fixed, it's really bothering to configure Spring, even with Spring Boot!
Found a problem that I was facing with not being able to access static resources.
For those who experience the same:
This behaviour (405 error) signifies that something is blocking the path to your static resources. This doesn't have to be /static or /public. It wont do anything.
In my case the problem was that a controller was blocking the /css path. To fix this a #RequestMapping(value = "/Somepath") annotation on the class lvl is needed to release the path for the static resources.
This worked for me and now I can access my static resources without any issues.
This can be a very annoying problem and someone can spend hours and days trying to figure this out. Hope this helps others to save their time
If there are alternative or other methods of preventing this behaviour that please mention in the comments
If you are trying to configure resource mapping through configuration class as you mentioned in comment, then it should be like this:
#EnableWebMvc
#ComponentScan(basePackages = {"org.company.yourpackage"})
#Configuration
public class AppConfig extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("classpath:/resources/static/").setCachePeriod(31556926);
}
}
this post also may help.
I was having the exact same issue, What helped me was adding:
enter code here
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.js</url-pattern>
</servlet-mapping>
OR
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>/js/*</url-pattern>
</servlet-mapping>
from this post
servlet for serving static content here