Repository won't Beanify - java

I have an error that I can't track down. I'm new so sorry if I missed this in the searches, but I tried several things and no luck.
UserApi.java:
package com.jsp.jsp;
import com.jsp.models.User;
import com.jsp.services.UserService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
#RestController
class UserApi {
private final UserService userService;
public UserApi(UserService userService) {
this.userService = userService;
}
#RequestMapping(value="/api/user", method=RequestMethod.POST)
public User createUser(
#RequestParam(value="name", required=true) String name,
#RequestParam(value="email", required=true) String email,
#RequestParam(value="password", required=true) String password,
#RequestParam(value="confirm", required=true) String confirm)
{
User u = this.userService.createUser(new User(name, email, password));
return u;
}
}
UserRepository.java:
package com.jsp.repositories;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Optional;
import com.jsp.models.User;
import org.springframework.data.repository.CrudRepository;
#Repository
public interface UserRepository extends CrudRepository<User, Long> {
List<User> findByEmail(String email);
Optional<User> findById(Long id);
List<User> findAll();
}
Server.java
package com.jsp.jsp;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
// import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#SpringBootApplication(scanBasePackages={"com.jsp.models","com.jsp.repositories","com.jsp.services"})
#RestController
public class Server {
public static void main(String[] args) {
SpringApplication.run(Server.class, args);
}
}
UserService.java
package com.jsp.services;
import java.util.List;
import com.jsp.models.User;
import com.jsp.repositories.UserRepository;
import org.springframework.stereotype.Service;
#Service
public class UserService {
private final UserRepository userRepository;
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public List<User> allUsers() {
return this.userRepository.findAll();
}
public User createUser(User u) {
return this.userRepository.save(u);
}
}
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.2.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.jsp</groupId>
<artifactId>jsp</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</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-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</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.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.2.5</version>
</dependency>
<dependency>
<groupId>org.mindrot</groupId>
<artifactId>jbcrypt</artifactId>
<version>0.4</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.11.7.RELEASE</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
So in short, when I run the above project in VSCode, it errors out with the following:
2019-02-23 19:07:52.744 WARN 25412 --- [ restartedMain]
ConfigServletWebServerApplicationContext : Exception encountered
during context initialization - cancelling refresh attempt:
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'userService' defined in file
[C:\Users\Alex\Documents\dojo\javatown\everything\target\classes\com\jsp\services\UserService.class]:
Unsatisfied dependency expressed through constructor parameter 0;
nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type 'com.jsp.repositories.UserRepository'
available: expected at least 1 bean which qualifies as autowire
candidate. Dependency annotations: {}
My understanding is that the repository I made should be automatically turned into a bean and then wire itself up to the service I made. However, that seems to be not happening. My example videos are using MySQL -- will that make a difference? Am I using the right driver for Postgres 11? I'm super lost.

Some remarks and suggestions:
1.add autowired annotation on your constructor, it is clearer what you need spring to do.
#Autowired
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
2. I don't understand #RestController annotation on your main class.
#SpringBootApplication(scanBasePackages {"com.jsp.models","com.jsp.repositories","com.jsp.services"})
#RestController --> THIS CAN BE REMOVED
public class Server {
public static void main(String[] args) {
SpringApplication.run(Server.class, args);
}
}
3.You should add #EnableJpaRepositories("com.jsp.repositories") on your spring boot application => it will scan the repositories in that package.
#SpringBootApplication(scanBasePackages {"com.jsp.models","com.jsp.repositories","com.jsp.services"})
#EnableJpaRepositories("com.jsp.repositories")
public class Server {
public static void main(String[] args) {
SpringApplication.run(Server.class, args);
}
}

Related

Consider defining a bean of type '...' in your configuration when using JPARepository

Ive been trying to follow a few basic examples to create a rest api to connect to a local mysql server
However I keep running to this error
Consider defining a bean of type 'org.example.database.MessagesRepository' in your configuration.
Here is my current project layout
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>org.example</groupId>
<artifactId>messagesApi</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.7</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</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>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Main.java
package org.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
#EnableAsync
#SpringBootApplication(exclude={DataSourceAutoConfiguration.class})
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
}
}
MessagesApi
package org.example.api;
import org.example.models.Messages;
import org.example.database.MessagesRepository;
import org.example.models.MessagesRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.util.List;
#Controller
#RequestMapping("/chats")
public class MessagesApi {
#Autowired
MessagesRepository messagesRepository;
#GetMapping("id")
public ResponseEntity<Messages> getAllChatsById(#RequestBody MessagesRequest messageRequest) {
return new ResponseEntity<>(messagesRepository.findByTextId(messageRequest.getTextId()), HttpStatus.OK);
}
#GetMapping("username")
public ResponseEntity< List<Messages>> getAllChatsByUserName(#RequestBody MessagesRequest messageRequest) {
return new ResponseEntity<>(messagesRepository.findByUserName(messageRequest.getUserName()), HttpStatus.OK);
}
#PostMapping
public ResponseEntity<Long> postMessage(#RequestBody Messages message ){
//make Id
Long id = 1234L;
message.setTextId(id);
messagesRepository.save(message);
return new ResponseEntity<>(id, HttpStatus.CREATED);
}
}
MessagesRespository
package org.example.database;
import org.example.models.Messages;
import org.springframework.data.repository.JpaRepository;
import java.util.List;
public interface MessagesRepository extends JpaRepository<Messages, Long> {
List<Messages> findByUserName(String userName);
Messages findByTextId(Long textId);
}
applications.properties
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=passWord
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.hibernate.ddl-auto=update
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
Ive tried adding
#EnableJpaRepositories
But kept getting
``Consider defining a bean named 'entityManagerFactory' in your configuration.
When removing
exclude={DataSourceAutoConfiguration.class}
I would get
Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.
Reason: Failed to determine a suitable driver class
I am not sure where to move forward from here
public interface MessagesRepository extends JpaRepository<Messages, Long> {
rather should be
#Repository
public interface MessagesRepository extends JpaRepository<Messages, Long> {
to make below code work
#Autowired
MessagesRepository messagesRepository;
also exclude from main class
exclude={DataSourceAutoConfiguration.class}
Sometimes spring is not able to scan your entity classes or your configuration classes so use this it will work fine
#SpringBootApplication
#ComponentScan({"org.example"})
#EntityScan("org.example")
#EnableJpaRepositories("org.example")
public class WebServiceApplication extends SpringBootServletInitializer {
}

Mockito testing void method which throws exception. Spring Boot, eclipse IDE

How to test a void method which throws an exception?
I've read many publications here and on others pages including Mockico docs form https://javadoc.io/static/org.mockito/mockito-core/3.12.4/org/mockito/Mockito.html#5. And my test still won't pass. I don't know what I'm doing wrong I always get red.
Maybe it is related to a wrongly implemented exception class.
Here is my code:
Repo:
import org.springframework.data.jpa.repository.JpaRepository;
import succeed.app.start.model.User;
public interface UserRepository extends JpaRepository<User, Long> {
}
Service interface:
public interface UserService {
void deleteUserById(long userId);
}
Service implementation:
#Service
public class UserServiceImpl implements UserService {
private UserRepository userRepository;
public UserServiceImpl(UserRepository userRepository) {
this.userRepository = userRepository;
}
#Override
public void deleteUserById(long userId) {
userRepository.findById(userId).orElseThrow(() -> new ResourceNotFoundException("User", "ID", userId));
userRepository.deleteById(userId);
}
}
Exception class:
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
#ResponseStatus(value = HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {
private final static long serialVersionUID = 1L;
private String resourceName;
private String fieldName;
private Object fieldValue;
public ResourceNotFoundException(String resourceName, String fieldName, Object fieldValue) {
super(String.format("%s not found with %s : %s", resourceName, fieldName, fieldValue));
this.resourceName = resourceName;
this.fieldName = fieldName;
this.fieldValue = fieldValue;
}
public String getResourceName() {
return resourceName;
}
public String getFieldName() {
return fieldName;
}
public Object getFieldValue() {
return fieldValue;
}
}
Test class:
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import static org.mockito.Mockito.doThrow;
import succeed.app.start.exception.ResourceNotFoundException;
import succeed.app.start.repository.UserRepository;
#ExtendWith(MockitoExtension.class)
public class UserServiceImplTest {
#Mock
UserRepository userRepository;
#Mock
UserServiceImpl userService;
#Test
#DisplayName("Should throw ResourceNotFoundException when user doesn't exist.")
void shouldThrowsResourceNotFoundException() {
final long nonExistingId = 12902450235L;
doThrow(new ResourceNotFoundException("User", "ID", nonExistingId)).when(userService).deleteUserById(nonExistingId);
userService.deleteUserById(nonExistingId);
}
}
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.5.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>succeed.app</groupId>
<artifactId>start</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>start</name>
<description>App to organize and achieve goals.</description>
<properties>
<java.version>11</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-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</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>
<!-- https://mvnrepository.com/artifact/org.mockito/mockito-junit-jupiter -->
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
There are a couple of things wrong here.
First, other than the message in the #Display annotation, your test doesn't really expect the exception to be thrown. You need to explicitly code this behavior, e.g. by using assertThrows.
Second, you're mocking the UserService, so the test won't really do anything - in the same method, you've defined some fake behavior and then tested it. Instead, you should mock the UserRepository and then make test that the UserService calls it correctly:
#ExtendWith(MockitoExtension.class)
public class UserServiceImplTest {
#Mock
UserRepository userRepository;
#InjectMocks
UserServiceImpl userService;
#Test
#DisplayName("Should throw ResourceNotFoundException when user doesn't exist.")
void shouldThrowsResourceNotFoundException() {
final long nonExistingId = 12902450235L;
doReturn(Optional.empty()).when(userRepository).findById(nonExistingId);
assertThrows(
ResourceNotFoundException.class,
() -> userService.deleteUserById(nonExistingId));
}
}

SpringBoot doesn't scan for components in microservices app

I'm coding microservices app based on Spring Cloud. I launched Eureka Server and now i'm coding a car-service. It worked when I didn't have any Autowiring in project. After adding Repository, Service and changing Controller the car-service doesn't launch.
When I added #SpringBootApplication("com.carrental.carservice.repository") application started but Rest API doesn't work and return 404. I tried with #Qualifier and naming Repository but still doesn't work.
There is an error when starting:
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 0 of constructor in com.carrental.carservice.service.impl.CarTypeServiceImpl required a bean of type 'com.carrental.carservice.repository.CarTypeRepository' that could not be found.
Action:
Consider defining a bean of type 'com.carrental.carservice.repository.CarTypeRepository' in your configuration.
And there is a WARN in logs:
Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.carrental.carservice.repository.CarTypeRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
pom.xml of car service
<?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">
<parent>
<artifactId>carrental</artifactId>
<groupId>com.carrental</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>car-service</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
<version>1.3.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.0.9.RELEASE</version>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<version>1.4.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<version>2.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.199</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.8</version>
</dependency>
</dependencies>
</project>
starting application file
package com.carrental.carservice;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.ComponentScan;
#SpringBootApplication
#EnableEurekaClient
//#ComponentScan("com.carrental.carservice.repository")
public class CarServiceApp {
public static void main(String[] args) {
SpringApplication.run(CarServiceApp.class, args);
}
}
controller
package com.carrental.carservice.controller;
import com.carrental.carservice.dto.CarTypeDto;
import com.carrental.carservice.model.entity.CarType;
import com.carrental.carservice.service.CarTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
#RestController
#RequestMapping("/car")
public class CarTypeController {
private final CarTypeService carTypeService;
#Autowired
public CarTypeController(CarTypeService carTypeService){
this.carTypeService = carTypeService;
}
#PostMapping("/cartype/add")
public ResponseEntity<CarTypeDto> addCarType(#Valid #RequestBody CarTypeDto dto){
CarType entity = Mapper.mapToCarTypeEntity(dto);
this.carTypeService.add(entity);
return new ResponseEntity<CarTypeDto>(Mapper.mapToCarTypeDto(entity), HttpStatus.CREATED);
}
#GetMapping
public String get(){
return "jajo";
}
}
service
package com.carrental.carservice.service.impl;
import com.carrental.carservice.model.entity.CarType;
import com.carrental.carservice.repository.CarTypeRepository;
import com.carrental.carservice.service.CarTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
#Service
public class CarTypeServiceImpl implements CarTypeService {
private final CarTypeRepository carTypeRepository;
#Autowired
public CarTypeServiceImpl(CarTypeRepository carTypeRepository){
this.carTypeRepository = carTypeRepository;
}
#Override
public void add(CarType carType) {
if(this.carTypeRepository.existsByName(carType.getName()))
return;
this.carTypeRepository.save(carType);
}
#Override
public List<CarType> getAll() {
return this.carTypeRepository.findAll();
}
#Override
public void update(CarType carType) {
if(this.carTypeRepository.existsById(carType.getId()))
this.carTypeRepository.save(carType);
}
#Override
public void delete(CarType carType) {
this.carTypeRepository.delete(carType);
}
}
repository
package com.carrental.carservice.repository;
import com.carrental.carservice.model.entity.CarType;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface CarTypeRepository extends JpaRepository<CarType, Long> {
boolean existsByName(String name);
CarType getByName(String name);
boolean existsById(Long id);
}
I tried a lot of stuff and still doesn't work. Can you help, please?
i think you need to use feignClient to avoid this exception.i had similar issue and added
#EnableFeignClients to my ApplicationClass and its dependency to your pom
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId
</dependency>

How to fix 'HTTP-404' error, during GET request in REST web service using spring boot

My sample spring boot REST web service gives 404 error, and I am not sure what went wrong
package com.in28minutes.springboot.studentservices;
#SpringBootApplication
public class StudentServicesApplication {
public static void main(String[] args) {
SpringApplication.run(StudentServicesApplication.class, args);
}
}
package com.in28minutes.springboot.controller;
#RestController
public class StudentController {
#Autowired
private StudentService studentService;
#GetMapping("/students/{studentId}/courses")
public List<Course> retrieveCoursesForStudent(#PathVariable String
studentId) {
return studentService.retrieveCourses(studentId);
}
#GetMapping("/students/{studentId}/courses/{courseId}")
public Course retrieveDetailsForCourse(#PathVariable String studentId,
#PathVariable String courseId) {
return studentService.retrieveCourse(studentId, courseId);
}
}
My Request from POSTMan REST request sender:
http://localhost:8080/students/stu1/courses/course1
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.in28minutes.springboot</groupId>
<artifactId>student-services</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>student-services</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-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</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>
Response:
{
"timestamp": "2018-12-28T02:48:00.185+0000",
"status": 404,
"error": "Not Found",
"message": "No message available",
"path": "/students/stu1/courses/course1"
}
As assumed, you have Controller classes in different package com.in28minutes.springboot.controller; and Spring boot main class in different package com.in28minutes.springboot.studentservices;
#SpringBootApplication
By default #SpringBootApplication will only scan from the package of the class that declares this annotation.
This is a convenience annotation that is equivalent to declaring #Configuration, #EnableAutoConfiguration and #ComponentScan.
If specific packages are not defined, scanning will occur from the package of the class that declares this annotation.
use #ComponentScan to scan controller package
#ComponentScan(basePackages = {"com.in28minutes.springboot.controller"})
#SpringBootApplication
public class StudentServicesApplication {
public static void main(String[] args) {
SpringApplication.run(StudentServicesApplication.class, args);
}
}
More Info : ref
The issue is resolved, #Component needed to be added to Service class, along with #ComponentScan in the main application class:
package com.in28minutes.springboot.service;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.springframework.stereotype.Component;
import com.in28minutes.springboot.model.Course;
import com.in28minutes.springboot.model.Student;
#Component
public class StudentService {
public List<Course> retrieveCourses(String studentId) {
Map<String, Course> courses = Student.getStudentObj(studentId).getCourses();
List<Course> courseList =
courses.values().parallelStream().collect(Collectors.toList());
return courseList;
}
public Course retrieveCourse(String studentId, String courseId) {
return Student.getStudentObj(studentId).getCourses().get(courseId);
}
}
package com.in28minutes.springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
#SpringBootApplication
#ComponentScan("com.in28minutes.springboot")
public class StudentServicesApplication {
public static void main(String[] args) {
SpringApplication.run(StudentServicesApplication.class, args);
}
}

Unsatisfied dependency expressed through constructor parameter 0

I was trying out a sample springboot project. But in the half way i got stuck up with this problem.
My Controller.java
package org.springbootdemo5.springbootdemo5.controler;
import org.springboot5.springbootdemo5.service.TaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class SampleRestController {
#Autowired
private TaskService taskService;
#GetMapping("/hello")
public String hello(){
return "Hello World!!!";
}}
My Task Service
package org.springboot5.springbootdemo5.service;
import java.util.ArrayList;
import java.util.List;
import javax.transaction.Transactional;
import org.springboot5.springbootdemo5.dao.TaskRepository;
import org.springboot5.springbootdemo5.model.Task;
import org.springframework.stereotype.Service;
#Service
#Transactional
public class TaskService {
private final TaskRepository taskRepository;
public TaskService(TaskRepository taskRepository) {
this.taskRepository = taskRepository;
}
public List<Task> findAll(){
List<Task> tasks = new ArrayList<>();
for(Task task : taskRepository.findAll()){
tasks.add(task);
}
return tasks;
}
public Task findTask(int id){
return taskRepository.findOne(id);
}
public void save(Task task){
taskRepository.save(task);
}
public void delete(int id){
taskRepository.delete(id);
}}
My Task Repository
package org.springboot5.springbootdemo5.dao;
import org.springboot5.springbootdemo5.model.Task;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Component;
public abstract class TaskRepository implements CrudRepository<Task, Integer>
{
}
And this my Initializer
package org.springbootdemo5.springbootdemo5;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
#SpringBootApplication
#ComponentScan("org.springboot5.springbootdemo5")
public class Springbootdemo5Application {
public static void main(String[] args) {
SpringApplication.run(Springbootdemo5Application.class, args);
}}
All the annotations are provided properly and pom.xml is also correct but still i am getting exception like
Exception
encountered during context initialization - cancelling refresh attempt:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error
creating bean with name 'taskService' defined in file
Unsatisfied dependency
expressed through constructor parameter 0; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type 'org.springboot5.springbootdemo5.dao.TaskRepository'
available: expected at least 1 bean which qualifies as autowire candidate.
Dependency annotations: {}
Description:
Parameter 0 of constructor in
org.springboot5.springbootdemo5.service.TaskService required a bean of type
'org.springboot5.springbootdemo5.dao.TaskRepository' that could not be
found.
Action:
Consider defining a bean of type
'org.springboot5.springbootdemo5.dao.TaskRepository' in your configuration.
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>org.springbootdemo5</groupId>
<artifactId>springbootdemo5</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>springbootdemo5</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.7.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-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.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>
<version>5.1.6</version>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jdbc</artifactId>
<version>9.0.0.M26</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
Anybody can solve this ?
Any help is always welcome.
Thank you.
Try changing your TaskRepository
to
public interface TaskRepository extends CrudRepository<Task, Integer>
Check the bean ID mentioned in the xml and the member in the Java file should be same , which is case sensitive.
config.xml
<bean id="reportServicePdf" class="my.local.spring.sprintlex.ReportService">
<constructor-arg name="numberOfPage" value="11" /> //<====Here
</bean>
ReportService.java:
public class ReportService {
#Value("100")
private int numberOfPage;//<====Here
::
::
}

Categories

Resources