I want to create a simple hello world app with SpringBoot where localhost:8080/welcome.html will show us Hello World.
I think I did all good but I can't see HelloWorld, just Whitelabel error page.
This is the link to my repo. If someone could check what is wrong I will be very happy!
https://github.com/BElluu/ElenXHello
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.springbelluu</groupId>
<artifactId>springboot-helloworld</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>springboot-helloworld</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.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>10</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-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</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>
SpringbootHelloworldApplication.java
package com.springbelluu.springboothelloworld;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class SpringbootHelloworldApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootHelloworldApplication.class, args);
}
}
TestController.java
package com.javainuse.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class TestController {
#RequestMapping("/welcome.html")
public ModelAndView firstPage() {
return new ModelAndView("welcome");
}
}
application.properties
spring.mvc.view.prefix:/WEB-INF/jsp/
spring.mvc.view.suffix:.jsp
For starters if you want to get starter with Spring Boot I strongly suggest NOT to use JSP. There are quite some limitations when using JSP, one of them is it doesn't work with jar packaging. Secondly it is a dated technology and doesn't receive much attention/updates anymore apart from keeping if functional in newer JEE versions. It is better to use something like Thymeleaf.
Next you are using snapshots versions for a version of Spring Boot that already is at 2.1.3.RELEASE (at the moment of writing).
That being said change your pom.xml to the following (fix version, remove JSP stuff and replace with Thymeleaf).
<?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.springbelluu</groupId>
<artifactId>springboot-helloworld</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>springboot-helloworld</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<java.version>10</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>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
NOTE: Because you now use a final version you don't need all the repositories in your pom.xml anymore!.
Now delete your JSP and create a welcome.html in src/main/resources/templates/. (You can actually remove your webapp directory in full.
<html>
<body>
<h1>Welcome! Spring Boot for ElenX</h1>
</body>
</html>
The setup you now have is more modern and easier to work with then JSP.
In your application.properties remove the spring.mvc.view properties as Spring Boot will automatically configure Thymeleaf with correct settings.
#BElluu ... your main application and Controller class are in different packages so componentscan is not working ...just check package level
package com.springbelluu.springboothelloworld;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class SpringbootHelloworldApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootHelloworldApplication.class, args);
}
}
package com.javainuse.controllers;
// use this package package com.springbelluu.springboothelloworld;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class TestController {
#RequestMapping("/welcome.html")
public ModelAndView firstPage() {
return new ModelAndView("welcome");
}
}
Go to below link by Spring Framework to create brand new Springboot Project:
https://start.spring.io/
or
1.Create a simple web application
Now you can create a web controller for a simple web application.
src/main/java/hello/HelloController.java
package hello;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
#RestController
public class HelloController {
#RequestMapping("/")
public String index() {
return "Greetings from Spring Boot!";
}
}
Create an Application class
Here you create an Application class with the components:
src/main/java/hello/Application.java
package hello;
import java.util.Arrays;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
#Bean
public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
return args -> {
System.out.println("Let's inspect the beans provided by Spring Boot:");
String[] beanNames = ctx.getBeanDefinitionNames();
Arrays.sort(beanNames);
for (String beanName : beanNames) {
System.out.println(beanName);
}
};
}
}
Here is SpringBoot Main class file Noting Changed Here.
-----------------------------------------
package com.Encee.SpringBoot_HelloWorld;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class SpringBootHelloWorldApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootHelloWorldApplication.class, args);
}
}
Here is controller package class
-----------------------------------------
package com.Encee.SpringBoot_HelloWorld.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class Controller {
#RequestMapping("/hello.html")
public String hello() {
return "Hello World";
}
}
-----------------------------------------
Now Main file run as Java Application will get your output.
SCREEN SHOT
Your issue has been fixed you can view the changes at my commit.
https://github.com/farooqrahu/ElenXHello/commits/master
Related
Hello I'm working with a Spring boot App connecting to a mongo db, my problem is that my endpoint are not working it seems that they are not found by Component scan. I'm have been crazy because I'm blocked to continue developing and I'm not able to identify the issue. All seems to be ok. I suppose that maybe is something related with the versions, but not pretty sure.
This is my controller:
package com.mercadolibre.mutants.controllers;
import com.mercadolibre.mutants.entities.Product;
import java.util.concurrent.CompletableFuture;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class ProductController {
private static final Logger LOGGER = LoggerFactory.getLogger(ProductController.class);
public static final String SHORTEN_URL_PATH = "/shorten";
public static final String URL_PATH = "/{id}";
#RequestMapping(value = SHORTEN_URL_PATH, method = RequestMethod.POST)
#ResponseStatus(HttpStatus.CREATED)
public CompletableFuture<String> shortenUrl(#RequestBody #Valid final Product shortenUrlDto, HttpServletRequest request) throws Exception {
LOGGER.info("Url to shorten: " );
CompletableFuture<String> shortenedUrl = null;
String localURL = request.getRequestURL().toString();
//shortenedUrl = shortUrlService.shortenURL(localURL, shortenUrlDto.getUrl());
LOGGER.info("Shortened url to: " + shortenedUrl);
return shortenedUrl;
}
#GetMapping(URL_PATH)
public CompletableFuture<String> retrieveOriginalUrl(#PathVariable String id) throws Exception {
LOGGER.info("short url to redirect: " + id);
//CompletableFuture<String> redirectUrlString = shortUrlService.getLongURLFromID(id);
// LOGGER.info("Original URL: " + redirectUrlString);
return null;
}
}
This is my Application class:
package com.mercadolibre.mutants;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication()
public class MutantsApplication {
public static void main(String[] args) {
SpringApplication.run(MutantsApplication.class, args);
}
}
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.1.16.BUILD-SNAPSHOT</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.mercadolibre</groupId>
<artifactId>mutants</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>mutants</name>
<description>Project for Java Challengue</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</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>
<!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-mongodb -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>2.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-releasetrain</artifactId>
<version>Lovelace-SR9</version>
<type>pom</type>
</dependency>
</dependencies>
<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>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
</pluginRepository>
<pluginRepository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
</project>
From the comments, I would say you have a problem with the docker configuration where you are deploying your api, I would do the next validations:
Check your api is being served in the 8080 inside your docker container.
Check if you have correctly configured your docker container so the 8080 port (or the one used by your api) is open.
Check if (for some strange reason) you don't have another api running in 8080 in the docker container.
Finally, get into the SSH of your container and then (if you are running some UNIX SO) make a CURL request to the url and check the answer.
Hopes this helps.
I am new to spring environment and was trying my hand at spring security, but I am unable to achieve basic authentication.
When I add spring security starter to maven dependencies I get default basic authentication by spring with user = user & password generated when you run the app. So far this works fine.
But now even though I have added SecurityConfiguration the default behaviour doesn't go away. If I try to access the resource through my new credentials I get Bad credentials message.
I am stuck here as for why spring still uses the default configuration, as with all the tutorials I have followed this works fine.
Referenced Tutorials
https://www.youtube.com/watch?v=rOnoKiH97Nc
https://www.youtube.com/watch?v=kiIMCzEN3c0
https://www.youtube.com/watch?v=3s2lSD50-JI
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.worldline.in</groupId>
<artifactId>maven_springboot_rest</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>maven_springboot_rest</name>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.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>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</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>
<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>
Application.java
package com.worldline.rest;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
// Tried component scan too -----
// https://stackoverflow.com/questions/38072517/unable-to-override-spring-boots-default-security-configuration
//#ComponentScan({"com.worldline.config"})
//some stackoverflow links suggest to exclude it for default behavior to go away
//#SpringBootApplication (exclude = {SecurityAutoConfiguration.class })
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Rest Controller
package com.worldline.rest;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.worldline.pojo.Greeting;
#RestController
public class GreetingController {
private final AtomicLong counter = new AtomicLong();
#RequestMapping("/greeting")
public Greeting greeting(#RequestParam(value="name", defaultValue = "world") String name )
{
return new Greeting(counter.incrementAndGet(), name);
}
}
Security Configuration
package com.worldline.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
#Configuration
#EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
/*http.authorizeRequests()
.anyRequest()
.fullyAuthenticated()
.and().httpBasic();
http.csrf().disable();*/
http.authorizeRequests()
.antMatchers("/greeting").hasRole("ADMIN");
}
/*#Override
protected void configure(AuthenticationManagerBuilder auth)
throws Exception {
auth.inMemoryAuthentication().withUser("sunny").password("admin").roles("admin");
}
*/
#Autowired
protected void configureGlobal(AuthenticationManagerBuilder auth) throws Exception
{
auth.inMemoryAuthentication().withUser("sunny").password("admin").roles("ADMIN");
}
}
I'm building a simple Spring application with the goal of returning "Hello world" as a foundation to build upon. I set up a clean project last night following this guide which worked and now I'm trying to bring an already existing project to the same functionality.
I have two files called ApplicationConfig.java and Controller.java tasked with returning a string when a certain URL is hit. When I visit localhost:8080 it renders my index.html with a link to the URL I wish to return a string at. When I visit the URL localhost:8080/home/greet it returns a 404.
My ApplicationConfig.java:
package application;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class ApplicationConfig {
public static void main(String[] args) {
SpringApplication.run (ApplicationConfig.class, args);
}
}
and my Controller.java
package controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
#RequestMapping("/home")
public class Controller {
#RequestMapping("/greet")
public String greeting() {
return "Hello";
}
}
As far as I see /home/greet/ should produce a page that just reads "Hello" but this isn't the case. What is the issue?
Here is my pom.xml and what my project structure looks like, should they be relevant.
<?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-rest-service</artifactId>
<version>0.1.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.0.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>
</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>
<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>
Your entrypoint class ApplicationConfig.java is in application package and Controller.java is in controller package.
SpringBoot scans for Spring components in the package( and sub-packages) where EntryPoint class is.
So move your controller to application or any nested package under application.
Step 1 : Add your ApplicationConfig.java in package abc.app;
Step 2 : Add your Controller.java in package abc.app.controller;.
Step 3 : add #ComponentScan("abc.app") in ApplicationConfig.java.
For Example :
ApplicationConfig.java:
package abc.app;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
#ComponentScan("abc.app")
public class ApplicationConfig {
public static void main(String[] args) {
SpringApplication.run (ApplicationConfig.class, args);
}
}
Controller.java :
package abc.app.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class Controller {
#RequestMapping("/greet")
public String greeting() {
return "Hello";
}
}
I Hope you Find your Right Solution here.
I am currently working on a POC to use Spring Boot with Spring Data JPA.
I want to fetch a record from the db using Spring Data JPA.
I am getting the below error
Error creating bean with name 'bookRepository': Cannot create inner bean '(inner bean)' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#2': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' is defined
Here are my configration class:
package com.boot.configration;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
#EnableAutoConfiguration
#ComponentScan
#EnableJpaRepositories
public class ApplicationStarter {
public static void main (String[] args) {
SpringApplication.run(ApplicationStarter.class, args);
}
}
Below is my reposatory
package com.boot.configration;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
#Repository
public interface BookRepository extends JpaRepository<Book, String> {
public Iterable<Book> findBooksByAuthor(#Param("author") String author);
}
And this is my controller
#RestController
public class BookController {
#Autowired
protected BookRepository bookRepository;
#RequestMapping(value = "/isbn")
#ResponseBody
public String book() {
Book book = bookRepository.findOne("2222222");
return "Book Name is = " + book.getTitle()+ " " + "Author is = " + book.getAuthor();
}
}
In the POM.xml i have the following dependencies:
<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>BOOT</groupId>
<artifactId>SpringBootProject</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.0.0.RC1</version>
</parent>
<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>
<name>SpringBootProject</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
</dependencies>
</project>
Please help me to solve this error
You could try using spring-boot 1.0.2.RELEASE?
I think you are missing database driver dependency.
As if you are using posgress you need to provide the driver jar.
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
it appears that the GA versions of
spring-core
spring-data-commons
spring-data-mongodb
as well as the most recent release candidate of
spring-boot-starter-web
spring-boot-autoconfigure
are not compatible.
what versions of these artifacts are compatible with each other?
I have a very basic Application.java that puts two objects into a MongoDB database and then takes them out and prints them to the screen.
import game.acorn.entities.Entity;
import game.acorn.mRepositoryInterfaces.EntityRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
#Configuration
#ComponentScan
#EnableAutoConfiguration
public class Application implements CommandLineRunner{
#Autowired
private EntityRepository repository;
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
public void run(String... args) throws Exception {
repository.deleteAll();
repository.save(new Entity("Jack", "Skellington"));
repository.save(new Entity("Blake", "Yarbrough"));
System.out.println("Entities found");
for (Entity entity : repository.findAll()){
System.out.println(entity);
}
System.out.println();
System.out.println("Entity by first name 'Jack'");
System.out.println(repository.findByFirstName("Jack"));
System.out.println();
System.out.println("Entity by first name 'Blake'");
System.out.println(repository.findByFirstName("Blake"));
}
}
When I run this application with
spring-core version 4.0.2.RELEASE
spring-data-commons version 1.5.0.RELEASE
spring-boot-starter-web version 1.0.0.RC4
spring-data-mongodb version 1.4.1.RELEASE
spring-boot-autoconfigure version 1.0.0.RC3
I end up getting a java.lang.NoClassDefFoundError at
org.springframework.boot.autoconfigure.data.AbstractRepositoryConfigurationSourceSupport.registerBeanDefinitions
which looks like
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata,
final BeanDefinitionRegistry registry) {
new RepositoryConfigurationDelegate(getConfigurationSource(), this.resourceLoader)
.registerRepositoriesIn(registry, getRepositoryConfigurationExtension());
}
with
new RepositoryConfigurationDelegate(getConfigurationSource(), this.resourceLoader)
being the line 58. It seems that there is a discrepancy between the version I am using and spring-boot's dependency.
So I try to up version my spring-data-commons to version 1.7.0.RELEASE
and then the class becomes available but I then get a java.lang.NoSuchMethodError at
org.springframework.boot.autoconfigure.data.AbstractRepositoryConfigurationSourceSupport$1.<init>(AbstractRepositoryConfigurationSourceSupport.java:66)
which looks like
private AnnotationRepositoryConfigurationSource getConfigurationSource() {
StandardAnnotationMetadata metadata = new StandardAnnotationMetadata(
getConfiguration(), true);
return new AnnotationRepositoryConfigurationSource(metadata, getAnnotation(),
this.environment) {
#Override
public java.lang.Iterable<String> getBasePackages() {
return AbstractRepositoryConfigurationSourceSupport.this
.getBasePackages();
};
};
}
with
return new AnnotationRepositoryConfigurationSource(metadata, getAnnotation(),
this.environment) {
being lines 65-66.
when I check out
org.springframework.data.repository.config.AnnotationRepositoryConfigurationSource
I find that the constructor
public AnnotationRepositoryConfigurationSource(AnnotationMetadata metadata, Class<? extends Annotation> annotation,
ResourceLoader resourceLoader, Environment environment) {
super(environment);
Assert.notNull(metadata);
Assert.notNull(annotation);
Assert.notNull(resourceLoader);
this.attributes = new AnnotationAttributes(metadata.getAnnotationAttributes(annotation.getName()));
this.metadata = metadata;
this.resourceLoader = resourceLoader;
}
expects one more argument than AbstractRepositoryConfigurationSourceSupport in spring-boot-autoconfigure gives it.
So, my question is, what versions of
spring-core
spring-data-commons
spring-boot-starter-web
spring-data-mongodb
spring-boot-autoconfigure
are compatible with each other?
my pom looks like
<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>1.0.0.RC3</version>
</parent>
<groupId>Master-Project</groupId>
<artifactId>Master-Project</artifactId>
<version>0.0.1-SNAPSHOT</version>
<description>Master Project for MongoDB and Spring</description>
<modules>
</modules>
<dependencies>
<!-- Spring Stuff -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>1.4.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons</artifactId>
<version>1.7.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>1.0.0.RC3</version>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>3.1</version>
</dependency>
</dependencies>
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>http://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<!--
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.3</source>
<target>1.1</target>
</configuration>
</plugin>
-->
<plugin>
<groupId>org.apache.maven.plugin</groupId>
<artifactId>maven-eclipse-plugin</artifactId>
<version>2.9</version>
<configuration>
<downloadSources>true</downloadSources>
<downloadJavadocs>true</downloadJavadocs>
</configuration>
</plugin>
</plugins>
</build>
</project>
When I remove the version tags on the dependencies I get the same no such method exception.
This is fixed if you use the Spring Boot dependencies pom (or the starter parent) with 1.0.0.RC5 or better.